Permutation of r elements out of n

谁说胖子不能爱 提交于 2019-12-25 01:06:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!