0

I am trying to generate an array containing the arrays of all possible combinations of an integer array; excluding the empty set and the original set itself. This is the code I have written. The outer loop runs until the number of elements to be included in a subset is equal to the number of elements in the original set. The outer for loop runs to add all elements of the new subset plus one additional element. For example, the loop should go through: A,B and then add C, then add D; generating A,B,C and A,B,D. Then the subset should shift to B,C and add D to give B,C,D. This process continues until all subsets are created. However I get an array index out of bounds exception.

    double pow = Math.pow(2.0, a.length);
    char[][] b = new char[(int)pow-2][a.length-1];

    int start = 0;
    int end = 0;
    int includedElements = 1;
    int curI = 0;

    while(includedElements<=a.length) {

        if(end == a.length) {
            start = 0;
            includedElements+=1;
            end = includedElements-1;
        }

        for(int h = end+1; h<a.length; h++) {
            b[curI] = new char[includedElements];

            for(int i = start, index = 0; i<=end; i++, index++) {
                b[curI][index] = a[i];
            }

            b[curI][b[curI].length] = a[h];
        }
        curI++;

        start+=1;
        end+=1;
    }

1 Answers1

1

I think you should first find out what you really want. There is a difference between combination and permutation (see here). When you know that, you can google for the exact term. I think what you want is permutation without repetition. This is an excercise you can solve recursively (example).

Community
  • 1
  • 1
Florian Lüdiger
  • 168
  • 3
  • 12