gpt4 book ai didi

java - 如何以相同的顺序从一维数组中的二维数组传输元素?

转载 作者:行者123 更新时间:2023-12-04 06:33:58 24 4
gpt4 key购买 nike

如何以相同的顺序从一维数组中的二维数组传输元素?

最佳答案

以下是我看到的最有可能的场景。

class nikhil {

public static int[] firstIndex(int[][] arr2d) {
int rows = arr2d.length;
if(rows == 0) return new int[0];
int cols = arr2d[0].length;
if(cols == 0) return new int[0];

int[] arr1d = new int[rows * cols];
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
arr1d[i * cols + j] = arr2d[i][j];
}
}
return arr1d;

}

public static int[] secondIndex(int[][] arr2d) {
int rows = arr2d.length;
if(rows == 0) return new int[0];
int cols = arr2d[0].length;
if(cols == 0) return new int[0];

int[] arr1d = new int[rows * cols];
for(int i = 0; i < cols; i++) {
for(int j = 0; j < rows; j++) {
arr1d[i * rows + j] = arr2d[j][i];
}
}
return arr1d;

}

public static int[] sorted(int[][] arr2d) {
int[] arr1d = firstIndex(arr2d);
java.util.Arrays.sort(arr1d);
return arr1d;
}

public static int[] scramble(int[][] arr2d) {
int[] arr1d = firstIndex(arr2d);
java.util.List<Integer> list = new java.util.ArrayList<Integer>();
for(int i : arr1d) list.add(i);
java.util.Collections.shuffle(list);

for(int i = 0; i < list.size(); i++) arr1d[i] = list.get(i).intValue();
return arr1d;

}

public static void main(String[] args) {
/*
5 4 6 10
3 1 9 12
8 2 7 0
*/
final int rows = 3;
final int cols = 4;
int[][] arr2d = new int[rows][cols];
arr2d[0][0] = 5;
arr2d[0][1] = 4;
arr2d[0][2] = 6;
arr2d[0][3] = 10;
arr2d[1][0] = 3;
arr2d[1][1] = 1;
arr2d[1][2] = 9;
arr2d[1][3] = 12;
arr2d[2][0] = 8;
arr2d[2][1] = 2;
arr2d[2][2] = 7;
arr2d[2][3] = 0;

int[] first = firstIndex(arr2d);
int[] second = secondIndex(arr2d);
int[] sorted = sorted(arr2d);
int[] scrambled = scramble(arr2d);

System.out.println(java.util.Arrays.toString(first));
System.out.println(java.util.Arrays.toString(second));
System.out.println(java.util.Arrays.toString(sorted));
// for oli
System.out.println(java.util.Arrays.toString(scrambled));

}

}

关于java - 如何以相同的顺序从一维数组中的二维数组传输元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5059200/

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