我正在尝试将数组的排列结果保存到2d数组中。假设我有一个数组{1,2,3,4},我创建了一个带有行的2D数组:N!和列4.是否可以将所有结果保存到2D数组中。例如,我有以下输出,我想将其保存到2D数组中
[1、2、3、4] [1、2、4、3]
答案 0 :(得分:0)
您的问题尚不清楚。万一您想知道如何创建和填充“ 2D数组”,这就是我可以告诉的内容:
import java.util.Arrays;
public class ArraysOfArrays {
public static void main(String[] args) {
// This is your '1D' array
int[] init = {1, 2, 3, 4};
//This is you '2D' array, 24 possibilities of 4 items in order
int[][] combinations = new int[24][4];
// fill your 2D array with the combinations you compute like that :
combinations[0] = new int[] {1,2,3,4};
combinations[1] = new int[] {1,2,4,3};
combinations[2] = new int[] {1,3,2,4};
combinations[3] = new int[] {1,3,4,2};
combinations[4] = new int[] {1,4,2,3};
combinations[5] = new int[] {1,4,3,2};
//...
combinations[23] = new int[] {4,3,2,1};
// or you can assign the individual values one by one :
combinations[0][0] = 1;
combinations[0][1] = 2;
combinations[0][2] = 3;
combinations[0][3] = 4;
System.out.println(Arrays.toString(combinations[3]));
}
}
希望有帮助!
答案 1 :(得分:0)
如果要在“ 2D”数组中存储许多数组,请按如下所示使用循环:
int size = 24; //this should be n! for permutations of n values.
combs[][] = new int[size][];
for (int i = 0; i < size; i++) {
combs[i] = getNextPermutationArray();
}
并且Java没有真正的多维数组。它只是具有数组等的数组。