I have an array of integers: n[]
.
Also, I have an array (Nr[]
) contains n.length
integers. I need to generate all combinations of n[]
in a following way:
/* let n.length == 3 and Nr[0] = 2, Nr[1] = 3, Nr[2] = 3 */
n = {0, 0, 0};
n = {1, 0, 0};
n = {2, 0, 0};
n = {0, 1, 0};
n = {0, 2, 0};
n = {0, 3, 0};
n = {0, 0, 1};
...
n = {1, 1, 0};
n = {1, 2, 0};
n = {1, 3, 0};
n = {2, 1, 0};
n = {2, 2, 0};
n = {2, 3, 0};
n = {1, 1, 1};
...
n = {0, 1, 1};
// many others
The goal is to find all combinations of n
, where n[i]
can be 0 to Nr[i]
.
I did not succeed... How to solve it in Java? Or not in Java...
You might want to use recursion, try all possibilities for each index, and recursively invoke with the subarray, "without" the last element.
invoke with:
will get you:
Note however - that using this method does print all elements as you describes, but in a different order then your example.
Note: Unlike the question logic, the following code is upper-exclusive, as is the standard in Java, e.g. input of
3
will count from 0 to 2 (inclusive), not 0 to 3.This can be done without recursion like this:
Test
Output
As an exercise in Java 8 streams, here is a class for iterating or streaming the permutations.
How to use:
All three produce the same output as above.
Here is the code: