Java 如何打印多维数组的所有索引?
如果只给出数组的维度,如何打印数组的所有索引。我已经递归地完成了,但无法在迭代中完成。我开始了,但只走了这么远Java 如何打印多维数组的所有索引?,java,arrays,algorithm,data-structures,Java,Arrays,Algorithm,Data Structures,如果只给出数组的维度,如何打印数组的所有索引。我已经递归地完成了,但无法在迭代中完成。我开始了,但只走了这么远 public static void print(int[] lengthOfDimension) { int[] index = new int[lengthOfDimension.length]; for (int i = 0; i < lengthOfDimension.length; i++) {
public static void print(int[] lengthOfDimension) {
int[] index = new int[lengthOfDimension.length];
for (int i = 0; i < lengthOfDimension.length; i++) {
for (int j = lengthOfDimension.length - 1; j > 0; j--) {
for (int m = lengthOfDimension[j] - 1; m > -1; m--) {
index[j] = m;
for (int l = 0; l < index.length; l++)
System.out.print(index[l] + " ");
System.out.println();
}
System.out.println();
index[j - 1] = lengthOfDimension[lengthOfDimension.length - i
- 1]
- i - 1;
}
// index[i] = lengthOfDimension[i] - 1;
}
}
预期产出为:
for a[] = {3,2,3}
0 0 0
0 0 1
0 0 2
0 1 0
0 1 1
0 1 2
1 0 0
1 0 1
1 0 2
1 1 0
1 1 1
1 1 2
2 0 0
2 0 1
2 0 2
2 1 0
2 1 1
2 1 2
我的理解是,您试图将所有可能的索引排列生成给定长度的一维数组 在注释中,数组的维数和数组中存储的数据的维数之间存在一些混淆。例如,
int[]a1={3,2,3}
是一个一维数组,存储的数据可以解释为三维空间中的一个点。另一方面,int[]]a2
声明了一个二维数组
下面使用的生成所有排列的技术与汽车中的旧里程表非常相似。从最低位置开始,我们不断将索引增加1,并检查它是否应该滚动。如果是这样,我们将其重置为0并继续。如果不是,那么我们有一个新的排列
下面是一些代码来说明:
public static void main(String[] args)
{
int a[] = { 3, 2 ,3};
indexPermutations(a);
}
public static void indexPermutations(int[] arr)
{
int n = arr.length;
int[] idx = new int[n];
while (true)
{
System.out.println(Arrays.toString(idx));
// generate the next permutation
int i = n-1;
for (; i >= 0; i--)
{
idx[i] += 1;
if (idx[i] < n) break;
idx[i] = 0;
}
// if the first index wrapped around then we're done
if (i < 0) break;
}
}
可能重复的预期输出是什么?对于a={2,2}0 0 0 0 1 0 1 1对于a[]={3,2,3}0 0 0 0 0 0 1 0 0 1 0 1 0 1 1 0 1 1 0 1 1 1 1 1 2 0 0 1 0 2 0 2请将预期输出添加到问题中,而不是作为注释。。。如图所示:(这里对于维度{3,2,3}所有排列只能是3*2*3=18。您是如何得出27个排列的。在您的代码中
if(idx[i]
这里有bug。n并不总是相同的。它可以是3或2,也可以是3,这取决于您迭代的元素
public static void main(String[] args)
{
int a[] = { 3, 2 ,3};
indexPermutations(a);
}
public static void indexPermutations(int[] arr)
{
int n = arr.length;
int[] idx = new int[n];
while (true)
{
System.out.println(Arrays.toString(idx));
// generate the next permutation
int i = n-1;
for (; i >= 0; i--)
{
idx[i] += 1;
if (idx[i] < n) break;
idx[i] = 0;
}
// if the first index wrapped around then we're done
if (i < 0) break;
}
}
[0, 0, 0]
[0, 0, 1]
[0, 0, 2]
[0, 1, 0]
[0, 1, 1]
[0, 1, 2]
[0, 2, 0]
[0, 2, 1]
[0, 2, 2]
[1, 0, 0]
[1, 0, 1]
[1, 0, 2]
[1, 1, 0]
[1, 1, 1]
[1, 1, 2]
[1, 2, 0]
[1, 2, 1]
[1, 2, 2]
[2, 0, 0]
[2, 0, 1]
[2, 0, 2]
[2, 1, 0]
[2, 1, 1]
[2, 1, 2]
[2, 2, 0]
[2, 2, 1]
[2, 2, 2]