I'm trying to go through all possible permutations of an array using a recursive function. The permutations don't need to be stored in memory. They are being processed right away by the recursive function.
The idea is that the recursive function has an argument 'used' which keeps track of the elements that are 'fixed' at this point in the recursion tree, and an argument 'free' which keeps track of the elements that are not fixed yet at this point (i.e. they will be rearranged in the recursion steps going down the tree from there). So the first time, the function is called with an empty 'used' array and a full 'free' array.
Somehow my code below doesn't work yet. It only processes the first permutation successfully.
const elements = [7, 23, 41, 65, 99]
const n = elements.length;
handlePermutations([], elements);
function handlePermutations(used, free) {
if (used.length<n) {
for (i = 0; i < free.length; i++) {
newUsed = used.concat(free[i]); // add element i from free to used
newFree = free.filter(x => x != free[i]) // remove element i from free
handlePermutations(newUsed, newFree);
}
} else {
// ... 'process' this permutation (do something useful with it) ...
}
}