Java 如何在二维数组中每隔一列交替元素的顺序
空2D数组Java 如何在二维数组中每隔一列交替元素的顺序,java,Java,空2D数组a应填充以下值: 1 8 9 16 17 2 7 10 15 18 3 6 11 14 19 4 5 12 13 20 我一直很难弄清楚如何颠倒列的顺序。这是我得到的最接近的结果: int [][] a = new int[4][5]; int count = 1; for(int c = 0; c < a[0].length; c++) { for(int r = 0; r < a.length; r++) {
a
应填充以下值:
1 8 9 16 17
2 7 10 15 18
3 6 11 14 19
4 5 12 13 20
我一直很难弄清楚如何颠倒列的顺序。这是我得到的最接近的结果:
int [][] a = new int[4][5];
int count = 1;
for(int c = 0; c < a[0].length; c++) {
for(int r = 0; r < a.length; r++) {
a[r][c] = count;
count++;
if(r% 2 == 0 && c % 2 != 0) {
count = 20;
a[r][c] = 20;
count--;
}
}
}
int[]a=新的int[4][5];
整数计数=1;
for(int c=0;c
您应该定义一个变量,该变量定义每次迭代时要移动的方向,我将其命名为符号
。若符号为正,则该列将向下填充,否则将向相反方向移动
int [][] a = new int[4][5];
int count = 1;
int sign = 1;
for(int j = 0 ; j < 5 ; j++){
if(sign==1)
for(int i = 0 ; i < 4 ; i++){
a[i][j]=count;
count++;
}
else
for(int i = 3 ; i >=0 ; i--){
a[i][j]=count;
count++;
}
sign *= -1;
}
您应该定义一个变量,该变量定义了在每次迭代中要移动的方向,我将其命名为
sign
。若符号为正,则该列将向下填充,否则将向相反方向移动
int [][] a = new int[4][5];
int count = 1;
int sign = 1;
for(int j = 0 ; j < 5 ; j++){
if(sign==1)
for(int i = 0 ; i < 4 ; i++){
a[i][j]=count;
count++;
}
else
for(int i = 3 ; i >=0 ; i--){
a[i][j]=count;
count++;
}
sign *= -1;
}
您所处的轨道是正确的,插入偶数列时只需将行反转即可
public static void main(String []args){
int count =1;
int columnCount =5;
int rowCount = 4;
int [][] a = new int[rowCount][columnCount];
for (int column = 0; column<columnCount; column ++ ) {
for (int row = 0; row <rowCount; row ++) {
if(column%2==0){
a[row][column] = count;
}else {
a[rowCount-row-1][column] =count;
}
count ++ ;
}
}
//validate results
for (int row = 0; row <rowCount; row ++) {
for (int column = 0; column<columnCount; column ++ ) {
System.out.print (a[row][column] +" ");
}
System.out.println();
}
}
您所处的轨道是正确的,插入偶数列时只需将行反转即可
public static void main(String []args){
int count =1;
int columnCount =5;
int rowCount = 4;
int [][] a = new int[rowCount][columnCount];
for (int column = 0; column<columnCount; column ++ ) {
for (int row = 0; row <rowCount; row ++) {
if(column%2==0){
a[row][column] = count;
}else {
a[rowCount-row-1][column] =count;
}
count ++ ;
}
}
//validate results
for (int row = 0; row <rowCount; row ++) {
for (int column = 0; column<columnCount; column ++ ) {
System.out.print (a[row][column] +" ");
}
System.out.println();
}
}
$java -Xmx128M -Xms16M HelloWorld
1 8 9 16 17
2 7 10 15 18
3 6 11 14 19
4 5 12 13 20