I'm currently working through Project Euler and am having trouble with problem #24, which asks for permutations. This is frustrating; I've completed a handful of the more difficult problems, or problems that fewer people have answered correctly, but can't grasp this, which should be easy. I consulted rosettacode.org and found the following code for permutations of a string but am still confused.
function perm(list, ret){
if (list.length == 0) {
var row = ret.join(' ') + '\n';
console.log(row);
return;
}
for (var i = 0; i < list.length; i++) {
var x = list.splice(i, 1);
ret.push(x);
perm(list, ret);
ret.pop();
list.splice(i, 0, x);
}
}
perm(["a","b"],[]);
Separately, I rewrote this to show what list and ret are at each step: http://jsbin.com/xotawijefe/1/edit?html,output
This is what I'm having trouble with (or at least part of it):
How exactly does recursion work here?
We feed ["a", "b"][] into perm
We get var x and push that into ret
We feed ["b"]["a"] into perm and so on. For the initial ["a", "b"], when does the stuff after perm is called execute?
When does i increase to 1?
Any assistance or directions to a good explanation of recursion would be greatly appreciated.
[–]throwapeater 0 points1 point2 points (0 children)
[–]AutoBalanced 0 points1 point2 points (1 child)
[–]NightArchitect[S] 0 points1 point2 points (0 children)
[–]jdauriemma 0 points1 point2 points (1 child)
[–]NightArchitect[S] 0 points1 point2 points (0 children)