I'm interested in performing a Cartesian product on n arrays. I can write the code if I know the number of arrays ahead of time. For example, given 2 arrays:
int[] a = new int[]{1,2,3};
int[] b = new int[]{1,2,3};
for(int i=0; i<=a.length; i++){
for(int j=0; j<=b.length; j++){
System.out.println(a[i]*b[j]);
}
}
The problem is that at runtime, I do not know the number of arrays. I may have 2 arrays, or I may have 100 arrays. Is there a way that I can do this? Thanks!
You can use recursion instead of iteration - but watch out - StackOverflowException may occur.
One way to approach this problem is to continuously reduce the number of arrays one at a time by noting that
Consequently, you could write a function like this one, which computes the Cartesian product of two arrays:
Now, you can use this function to keep combining together pairs of arrays into one single array containing the overall Cartesian product. In pseudocode:
And, as actual Java:
The problem with this approach is that it uses memory proportional to the total number of elements you produce. This can be a really huge number! If you just want to print all of the values out one at a time without storing them, there is a more efficient approach. The idea is that you can start listing off all possible combinations of indices in the different arrays, then just go multiply together the values at those positions. One way to do this is to maintain an "index array" saying what the next index to look at is. You can move from one index to the next by "incrementing" the array the same way you would increment a number. Here's some code for that:
This uses only O(L) memory, where L is the number of arrays you have, but produces potentially exponentially many values.
Hope this helps!