views:

60

answers:

2

I have a 2d array, let's say like this :

2   0   8   9
3   0  -1  20
13  12  17  18
1   2   3   4
2   0   7   9

How to create an array reduced by let's say 2nd row and third column?

2   0    9
13  12   18
1   2    4
2   0    9
+1  A: 
public class TestMe {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub

    int array[][] = {{2,0,   8,   9,},
                        {3,   0,  -1,  20},
                        {13,  12,  17,  18},
                        {1,   2,   3,   4,},
                        {2,   0,   7,   9}};

    for(int i=0; i<array.length;i++){
        if(i == 1 ){
            continue;
        }
        for(int j=0; j<array[i].length;j++){
            if(j==2){
                continue;
            }
            System.out.print(array[i][j]+" ");
        }
        System.out.println("");
    }


}

}

Upul
you may want to try != ...
this way I can print it only but it does not give me the reduced array :/
owca
+4  A: 

Removing rows and columns in arrays are expensive operations because you need to shift things, but these methods do what you want:

static int[][] removeRow(int[][] data, int r) {
    int[][] ret = new int[data.length - 1][];
    System.arraycopy(data, 0, ret, 0, r);
    System.arraycopy(data, r+1, ret, r, data.length - r - 1);
    return ret;
}

static int[][] removeColumn(int[][] data, int c) {
    for (int r = 0; r < data.length; r++) {
        int[] row = new int[data[r].length - 1];
        System.arraycopy(data[r], 0, row, 0, c);
        System.arraycopy(data[r], c+1, row, c, data[r].length - c - 1);
        data[r] = row;
    }
    return data;
}

You may want to investigate other data structures that allow for cheaper removals, though, i.e. doubly-linked lists. See, for example, Dancing Links.

polygenelubricants
+1 for suggesting a different data structure.
Cam