gpt4 book ai didi

java - 尝试交换矩阵中的偶数/奇数行(Java)

转载 作者:行者123 更新时间:2023-12-01 09:17:03 24 4
gpt4 key购买 nike

我试图交换矩阵中的偶数行和奇数行索引,以便所有偶数行都位于顶部,所有奇数行都位于底部。我事先创建了矩阵。

这是我的行交换代码:

    int numberOfEvenRowIndices = 0;
if(matrix.length%2.0 == 0){
numberOfEvenRowIndices = matrix.length/2 - 1;
}
else{
numberOfEvenRowIndices = (int) (matrix.length/2.0 - 0.5);
}
for(int m = 0; m < numberOfEvenRowIndices; m++){
for (int k = 2; k < rows; k++){
if((matrix[k][0]/10)%2 == 0.0){
int firstEvenRow = k;

for (int i = 0; i < matrix[firstEvenRow].length; i++){
//store value of first even row index
int temp = matrix[firstEvenRow][i];
//swap value of first even row with first odd row
matrix[firstEvenRow][i] = matrix[k-1][i];
matrix[k-1][i] = temp;}
}
}

for( int i = 0 ; i < rows ; i++){
for( int j = 0 ; j < columns ; j++){
System.out.printf("%4s", matrix[i][j]);
}
System.out.println();
}
}

它输出:

0   1   2   3   4   5   6   7

40 41 42 43 44 45 46 47

20 21 22 23 24 25 26 27

60 61 62 63 64 65 66 67

10 11 12 13 14 15 16 17

30 31 32 33 34 35 36 37

50 51 52 53 54 55 56 57

70 71 72 73 74 75 76 77

我需要按顺序排列行(从上到下:0、20、40、60、10、30、50、70)如有任何帮助,我们将不胜感激。

最佳答案

这是使用List的一种解决方案

    ArrayList<Integer[]> result = new ArrayList<Integer[]>();
ArrayList<Integer[]> odd = new ArrayList<Integer[]>();

for (int i = 0, s = matrix.length; i < s; i++) {
if (i % 2 == 2) {
result.add(matrix[i]);
} else {
odd.add(matrix[i]);
}
}
result.addAll(odd);
Integer[][] resultMatrix = result.toArray(new Integer[result.size()][]);

最后你将得到“排序”矩阵作为二维数组。

关于java - 尝试交换矩阵中的偶数/奇数行(Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40472807/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com