Hi, I am new on Processing and I am struggling with Java.
I am trying to use Heap’s algorithm to get the list of all the permutations of numbers.
I want to store that list so I wan use it as a matrix for animation.
I have tried many different ways and types but I can’t fill it correctly.
As I am stuck, I would appreciate some help.
Here what I have:
// https://en.wikipedia.org/wiki/Heap%27s_algorithm#Details_of_the_algorithm
void heapPermutations(int k, IntList l, ArrayList<IntList> a) {
if (k == 1) {
a.add(l); // Side effect : current permutation storage
printArray(l); // For testing purposes
println("--");
} else {
heapPermutations(k-1, l, a);
for (int i=0; i<k-1; i++) {
if (k % 2 == 0) {
swapInt(i, k-1, l);
} else {
swapInt(0, k-1, l);
}
heapPermutations(k-1, l, a);
}
}
};
To store the stuff, I wrote that :
IntList base = new IntList(0, 1, 2);
ArrayList<IntList> permutations = new ArrayList<IntList>(factorial(base.size()));
heapPermutations(base.size(), base, permutations);
for(IntList perm : permutations) {
printArray (perm);
}
Current output:
IntList size=3 [ 0, 1, 2 ]
--
IntList size=3 [ 1, 0, 2 ]
--
IntList size=3 [ 2, 0, 1 ]
--
IntList size=3 [ 0, 2, 1 ]
--
IntList size=3 [ 1, 2, 0 ]
--
IntList size=3 [ 2, 1, 0 ]
--
IntList size=3 [ 2, 1, 0 ]
IntList size=3 [ 2, 1, 0 ]
IntList size=3 [ 2, 1, 0 ]
IntList size=3 [ 2, 1, 0 ]
IntList size=3 [ 2, 1, 0 ]
IntList size=3 [ 2, 1, 0 ]
Desired output:
IntList size=3 [ 0, 1, 2 ]
--
IntList size=3 [ 1, 0, 2 ]
--
IntList size=3 [ 2, 0, 1 ]
--
IntList size=3 [ 0, 2, 1 ]
--
IntList size=3 [ 1, 2, 0 ]
--
IntList size=3 [ 2, 1, 0 ]
--
IntList size=3 [ 0, 1, 2 ]
IntList size=3 [ 1, 0, 2 ]
IntList size=3 [ 2, 0, 1 ]
IntList size=3 [ 0, 2, 1 ]
IntList size=3 [ 1, 2, 0 ]
IntList size=3 [ 2, 1, 0 ]
NB. factorial
is obviously the factorial function for an integer.