Graham Slick
Graham Slick

Reputation: 6870

Add column at a particular index in 2D Array without deleting any other column

I created a matrix/2D array:

int [][] matrix; 

Which looks something like this:

0010111100
1011110111
0100101101
0101010001
0000010011
0010110101
0101101001
1010010110
0111010001
0101011101

How can I add this column:

0
0
0
0
1
0
0
0
0
0

at a given index, without deleting the last column ? The matrix would then have 11 columns instead of 10.

Upvotes: 1

Views: 291

Answers (1)

George
George

Reputation: 3845

Trivial solution: Create a new 2D array with one more column and copy all the values to the new array. Below I show one simple implementation of what I'm talking about. I omitted any kind of checks. Also, I assume that all rows have the same number of columns.

public static int[][] addColumn(int[][] matrix, int[] column, int index) {
    int[][] result = new int[matrix.length][matrix[0].length + 1];

    for (int r = 0; r < matrix.length; ++r) {
        System.arraycopy(matrix[r], 0, result[r], 0, index);
        result[r][index] = column[r];
        System.arraycopy(matrix[r], index, result[r], index + 1, matrix[0].length - index);
    }

    return result;
}

If you only add columns and rows are fixed it may be better to have a List of int arrays, where each element is a column of your matrix. Then, adding a column at a given position is much easier and more efficient, as you don't have to copy the whole matrix. I would also suggest wrapping it in a class and provide useful methods (like getters/setters if needed).

Upvotes: 1

Related Questions