How to get all possible combinations from two arrays? How to get all possible combinations from two arrays? arrays arrays

How to get all possible combinations from two arrays?


Use a triple loop:

for (int i=0; i < operators.length; ++i) {    for (int j=0; j < operators.length; ++j) {        for (int k=0; k < operators.length; ++k) {            System.out.println(numbers[0] + operators[i] + numbers[1] + operators[j] +                numbers[2] + operators[k] + numbers[3]);        }    }}

You essentially want to take the cross product of the operators vector (if it were a vector). In Java, this translates to a triply-nested set of loops.


While @TimBiegeleisen solution would work like a charm, its complexity might be an issue. The better approach would be a code like this:

static void combinationUtil(        int[] arr, int n, int r, int index, int[] data, int i) {    // Current combination is ready to be printed, print it     if (index == r) {        for (int j = 0; j < r; j++)            System.out.print(data[j] + " ");        System.out.println("");        return;    }    // When no more elements are there to put in data[]     if (i >= n)        return;    // current is included, put next at next location     data[index] = arr[i];    combinationUtil(arr, n, r, index + 1, data, i + 1);    // current is excluded, replace it with next (Note that     // i+1 is passed, but index is not changed)     combinationUtil(arr, n, r, index, data, i + 1);}
// The main function that prints all combinations of size r // in arr[] of size n. This function mainly uses combinationUtil() static void printCombination(int arr[], int n, int r) {    // A temporary array to store all combination one by one     int data[] = new int[r];    // Print all combination using temprary array 'data[]'     combinationUtil(arr, n, r, 0, data, 0);}

Source: GeeksForGeeks and my IDE :)


This sounds like a textbook case for a recursive solution:

public static void combineAndPrint(String[] pieces, String[] operators) {    if (pieces.length < 1) {        // no pieces? do nothing!    } else if (pieces.length == 1) {        // just one piece? no need to join anything, just print it!        System.out.println(pieces[0]);    } else {        // make a new array that's one piece shorter        String[] newPieces = new String[pieces.length - 1];        // copy all but the first two pieces into it        for (int i = 2; i < pieces.length; i++) {            newPieces[i - 1] = pieces[i];        }        // combine the first two pieces and recurse        for (int i = 0; i < operators.length; i++) {            newPieces[0] = pieces[0] + operators[i] + pieces[1];            combineAndPrint(newPieces, operators);        }    }}public static void main(String[] args) {    String[] operators = {"+", "-", "*"};    String[] numbers = {"48", "24", "12", "6"};    combineAndPrint(numbers, operators);}

Try it online!

BTW, to generalize this method so that you can do more things with the generated expressions than just printing them, I would recommend making it accept an extra Consumer<String> parameter. That is, you could rewrite the method declaration as:

public static void combine(String[] pieces, String[] operators, Consumer<String> consumer) {

and replace the System.out.println(pieces[0]) with consumer.accept(pieces[0]) and the recursive call to combineAndPrint(newPieces, operators) with combine(newPieces, operators, consumer). Then just call it from your main method e.g. as:

combine(numbers, operators, s -> System.out.println(s));

Try it online!

(Of course, doing it in this more flexible way requires a somewhat modern Java version — Java 8 or later, to be specific — whereas the first example I showed above should work on even ancient versions all the way down to Java 1.0. Maybe in some future version of Java we'll get proper support for coroutines and generators, like Python and Kotlin and even modern JS already have, and then we won't even need to pass the consumer around any more.)