[英]how to reduce 2d array
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
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, ie doubly-linked lists. 但是,您可能希望研究其他允许便宜删除的数据结构,即双向链接列表。 See, for example, Dancing Links . 参见,例如, 跳舞链接 。
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("");
}
}
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.