【问题标题】:Easier way to do many nested for loops做许多嵌套 for 循环的更简单方法
【发布时间】:2016-12-31 02:36:04
【问题描述】:

我需要生成所有可能的颜色组合的列表(我有 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);

                    }
                }
            }
        }
    }

【问题讨论】:

标签: java for-loop


【解决方案1】:

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

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

【讨论】:

  • 有人能解释一下吗?
  • @KaminPallaghy 更新了我的答案。如果还不清楚,请告诉我。
  • 谢谢。这要容易得多
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-26
  • 2012-06-23
相关资源
最近更新 更多