0

I need to generate a list of all possible combinations of colors(I have 8 different colors) and would like to specify the length of the output, without going into the code and adding another loop.

for (int s1 = 0; s1 < kinds.length; s1++) {
        for (int s2 = 0; s2 < kinds.length; s2++) {
            for (int s3 = 0; s3 < kinds.length; s3++) {
                for (int s4 = 0; s4 < kinds.length; s4++) {
                    for (int s5 = 0; s5 < kinds.length; s5++) {
                        String[] guess = new String[length];
                        guess[0] = colors[s1];
                        guess[1] = colors[s2];
                        guess[2] = colors[s3];
                        guess[3] = colors[s4];
                        guess[4] = colors[s5];
                        Possible.add(guess);

                    }
                }
            }
        }
    }
EJK
  • 12,332
  • 3
  • 38
  • 55
  • Possible duplicate of [Getting every possible permutation of a string or combination including repeated characters in Java](http://stackoverflow.com/questions/5113707/getting-every-possible-permutation-of-a-string-or-combination-including-repeated) – ACascarino Dec 31 '16 at 02:41
  • You only need 1 loop just like you increment a clock. – Enzokie Dec 31 '16 at 02:50
  • Possible duplicate of [Combinatorics: generate all “states” - array combinations](http://stackoverflow.com/q/9632677/5221149) – Andreas Dec 31 '16 at 03:38
  • Possible duplicate of [how to write n-level embeded loop with java](http://stackoverflow.com/q/40954694/5221149) – Andreas Dec 31 '16 at 03:45
  • Thanks, i will look in to your answer @Andreas; – Kamin Pallaghy Jan 01 '17 at 03:42

1 Answers1

0

You can use recursion instead of loop. The general idea is all possible combinations can be generated from the all possible first colors concat with the combinations of the rest.

private static List<String> possibles = new ArrayList<>();

private static void combi(char[] arr, char[] out, int start, int end, int index, int length) {
    if (index == length) {
        possibles.add(new String(out));
        return;
    }

    for (int i = start; i <= end && end - i + 1 >= length - index; i++) {
        out[index] = arr[i];
        combi(arr, out, i + 1, end, index + 1, length);
    }
}

private static void compute(char[] colors, int length) {
    char[] output = new char[length];
    combi(colors, output, 0, colors.length - 1, 0, length);
}

public static void main(String[] args) {
    char[] colors = {'a', 'b', 'c', 'd', 'e'};
    int length = 3;
    compute(colors, length);

    for (String possible : possibles) {
        System.out.println(possible);
    }
}
pt2121
  • 11,720
  • 8
  • 52
  • 69