如何以相同的顺序从1-d数组中的2-d数组传输元素?
答案 0 :(得分:2)
以下是我看到的最可能的情景。
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));
}
}
答案 1 :(得分:1)
虽然已经回答here,但我将在此处发布解决方案示例。
假设您有一个2D数组,例如originalArray [ ][ ]
int a [] = {1,2,6,7,2};
int b [] = {2,44,55,2};
int c [] = {2,44,511,33};
int originalArray [][] = new array[][]{a,b,c};
案例1:
如果以上所有1D数组都具有相同的长度,那么您可以这样继续:
int[] newArray = new int[3 * a.length];
int index = 0;
for (int n = 0; n < a.length; n++) {
newArray[index++] = a[n];
newArray[index++] = b[n];
newArray[index++] = c[n];
}
案例2:
如果上述所有1D数组的长度都不同,那么您可以这样做,
int[] newArray = new int[a.length + b.length + c.length];
System.arrayCopy(a, 0, newArray, 0, a.length);
System.arrayCopy(b, 0, newArray, a.length, b.length);
System.arrayCopy(c, 0, newArray, a.length + b.length, c.length);