I’m sure there is a CS term for what I’m trying to accomplish but I’m not sure what it is. I have three arrays, let’s call them a, b, and c. I am iterating through every possible combination of the arrays, which would be a*b*c iterations.
I am passing a function an int of the current iteration (such that iteration goes from 0 to a*b*c-1) and the length of a, b, and c. I want that function to be able to print out every unique permutation of indices, calculated from just the iteration count and the lengths of a, b, and c.
This is what I have now:
class Test {
public static void printIndices(int i, int a, int b, int c) {
System.out.println(i%a + ", " + (i+1)%b + ", " + (i+2)%c);
}
public static void main(String[] args) {
int a[] = new int[2];
int b[] = new int[2];
int c[] = new int[3];
int iterations = a.length * b.length * c.length;
for (int i=0; i < iterations; i++){
printIndices(i, a.length, b.length, c.length);
}
}
}
It generates this output:
0, 1, 2
1, 0, 0
0, 1, 1
1, 0, 2
0, 1, 0
1, 0, 1
0, 1, 2
1, 0, 0
0, 1, 1
1, 0, 2
0, 1, 0
1, 0, 1
As you can see there are duplicates. I want the output to be:
0, 0, 0
1, 0, 0
0, 1, 0
1, 1, 0
0, 0, 1
1, 0, 1
0, 1, 1
1, 1, 1
0, 0, 2
1, 0, 2
0, 1, 2
1, 1, 2
(the order is unimportant, as long as every permutation is there with no duplicates).
Obviously my output line is wrong:
System.out.println(i%a + ", " + (i+1)%b + ", " + (i+2)%c);
What are the correct operations to get the output I am looking for?
I understand that this code is a bit silly looking and it’s not at all what I’m actually doing, but it demonstrates the case well.
As mentioned in the comments you are looking for the Cartesian product.
Your approach with modular arithmetic almost works. You need only a few modifications to get the correct result:
See it working online: ideone