更容易的方法来做许多嵌套for循环

时间:2016-12-31 02:36:04

标签: java for-loop

我需要生成所有可能的颜色组合的列表(我有8种不同的颜色),并且想要指定输出的length,而不需要进入代码并添加另一个循环。

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);

                    }
                }
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

您可以使用递归而不是循环。一般的想法是所有可能的组合都可以从所有可能的第一种颜色与其余颜色的组合生成。

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);
    }
}