Sagar Sagar - 1 month ago 7
Java Question

Populating a 2D array with every possible combination of 3 math operators

I want to build a 2D array that can hold every 3 item combination of the four math operators (+-*/)
The array is supposed to look something like this

[-, - , -]

[-, *, *]

[-, /, /]



...

[/, *, *]

[/, /, /]


However I'm running into some problems. My code, when just printing the combinations, is printing each of the combinations 3 times each. Second, I'm not too sure how to get each operator into its place in the array.


Here's my code



String[][] allOps = new String[27][3];
int count = 1;

String[] ops = new String[] {"+","-","*","/"};
for (int x=1;x<4;x++)
{
for (int y=1;y<4;y++)
{
for (int z=1;z<4;z++)
{


//System.out.println(ops[x] + " " + ops[y] + " " + ops[z] + " " + count);
//count++;
}
}
}


Is there any way to get each operator in it's specific place ([ * ][ * ] [ * ]) using a for loop?

Answer

Try this, you need to construct the new array with the operators and add it in the index starting from zero, also the maximum combination you will get is 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));

With java8 streams

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

Combinations

[[+, +, +], [+, +, -], [+, +, *], [+, +, /], [+, -, +], [+, -, -], [+, -, *], [+, -, /], [+, *, +], [+, *, -], [+, *, *], [+, *, /], [+, /, +], [+, /, -], [+, /, *], [+, /, /], [-, +, +], [-, +, -], [-, +, *], [-, +, /], [-, -, +], [-, -, -], [-, -, *], [-, -, /], [-, *, +], [-, *, -], [-, *, *], [-, *, /], [-, /, +], [-, /, -], [-, /, *], [-, /, /], [*, +, +], [*, +, -], [*, +, *], [*, +, /], [*, -, +], [*, -, -], [*, -, *], [*, -, /], [*, *, +], [*, *, -], [*, *, *], [*, *, /], [*, /, +], [*, /, -], [*, /, *], [*, /, /], [/, +, +], [/, +, -], [/, +, *], [/, +, /], [/, -, +], [/, -, -], [/, -, *], [/, -, /], [/, *, +], [/, *, -], [/, *, *], [/, *, /], [/, /, +], [/, /, -], [/, /, *], [/, /, /]]
Comments