試試這個,你需要構建新的數組與運營商,並在索引中添加它從零開始,你也將得到最大的組合是64
String[][] allOps = new String[64][3];
int count = 0;
for (int x = 0; x < 4; x++) {
for (int y = 0; y < 4; y++) {
for (int z = 0; z < 4; z++) {
allOps[count][0] = ops[x];
allOps[count][1] = ops[y];
allOps[count][2] = ops[z];
count++;
}
}
}
System.out.println(count);
System.out.println(Arrays.deepToString(allOps));
隨着java8流
String[] ops = new String[] { "+", "-", "*", "/" };
List<String> opsList = Arrays.asList(ops);
String[][] combinations = opsList.stream()
.flatMap(x -> opsList.stream().flatMap(y -> opsList.stream().map(z -> new String[] { x, y, z })))
.toArray(String[][]::new);
System.out.println(Arrays.deepToString(combinations));
組合
[[+, +, +], [+, +, -], [+, +, *], [+, +, /], [+, -, +], [+, -, -], [+, -, *], [+, -, /], [+, *, +], [+, *, -], [+, *, *], [+, *, /], [+, /, +], [+, /, -], [+, /, *], [+, /, /], [-, +, +], [-, +, -], [-, +, *], [-, +, /], [-, -, +], [-, -, -], [-, -, *], [-, -, /], [-, *, +], [-, *, -], [-, *, *], [-, *, /], [-, /, +], [-, /, -], [-, /, *], [-, /, /], [*, +, +], [*, +, -], [*, +, *], [*, +, /], [*, -, +], [*, -, -], [*, -, *], [*, -, /], [*, *, +], [*, *, -], [*, *, *], [*, *, /], [*, /, +], [*, /, -], [*, /, *], [*, /, /], [/, +, +], [/, +, -], [/, +, *], [/, +, /], [/, -, +], [/, -, -], [/, -, *], [/, -, /], [/, *, +], [/, *, -], [/, *, *], [/, *, /], [/, /, +], [/, /, -], [/, /, *], [/, /, /]]
數組是0索引。您在'for'循環中的索引應該從0開始。 – 4castle
您有一個錯字。第三個值應該使用'ops [z]'而不是'ops [y]'。 [它工作正常](https://ideone.com/L2p0GE)。 – 4castle
@ 4castle但是,如果你仔細觀察你的輸出,你會發現有重複的,例如' - - +'和'+ - -'和' - + -' ...不確定OP是否在意這一點,但只是想指出這一點。 –