Hello,
I have this solution for coming up with all the permutations of an array of numbers.
Here is my code:
function getPermutations(arr) {
let result = [];
let copy = arr.slice();
function permute(index) {
if (index === arr.length) {
result.push(copy.slice());
return;
}
for (let i = index; i < copy.length; i++) {
[copy[index], copy[i]] = [copy[i], copy[index]]; *
permute(index + 1);
[copy[index], copy[i]] = [copy[i], copy[index]]; **
}
}
permute(0);
return result;
}
I am having some trouble understanding what is going on inside the for
loop. Line * swaps one index
of the copied array with an index i
, and then recursively calls permute()
with the next index
until it reaches the base case index === arr.length - 1
, when it then pushes the permuted array to result
. I am guessing that all these recursive calls return before line ** runs, when the array is restored to its original [?] order and we move on to the next iteration of the for
loop.
If that is the case, why can’t I replace line ** with copy = arr.slice()
? It doesn’t work when I do that.
If line * is swapping one pair, waiting for all the recursive calls of permute()
to return, and then swapping the pair back, wouldn’t every subsequent iteration of the for
loop be acting on the original array?
Is there something I’m missing?
Thank you.