问题
I have the following code for permutation. But it is throwing the below error.
11111
21111
31111
41111
51111
61111
71111
81111
91111
01111
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at Permutation.main(nPr_3.java:22)
The code is
HashSet<Integer[]> set = new HashSet<Integer[]>();
int[] values = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
int n = values.length;
int r = 5;
int i[] = new int[r];
int rc = 0;
for(int j=0; j<Math.pow(n,r); j++)
{
Integer[] e = new Integer[r];
while(rc<r)
{
e[rc] = values[i[rc]];
System.out.print(values[i[rc]]);
rc++;
}
System.out.println();
rc = 0;
set.add(e);
while(rc<r)
{
if(i[rc]<n)
{
i[rc]++;
break;
}
rc++;
}
}
Thanks.
回答1:
When the exception is thrown i[ rc ]( ==i[ 0 ] ) has been incremented in the line i[rc]++ until the value 10. But values contains only elements with indecees 0..9.
来源:https://stackoverflow.com/questions/11250250/permutation-of-r-elements-out-of-n