Programming Questions

Finding Permutations via Recursion

I'm trying to solve Prime Checker, and in order to do so I need to find all permutations of the given number.
My main problem with my code is the "scrambler" function, whose purpose is to modify "options" to be an array of each possible combination of the given numbers.
However I get the following error:
TypeError: undefined is not a function
This error only kicks up when the recursive call on 'scrambler' is involved. If I remove it it functions properly. I've spent all day looking at this thing, and I can't figure out why it's not working. Any help would be appreciated. (I'm sure I could implement it in other ways, but at this point I want to know why it's broken).
Here's the code.

```
function PrimeChecker(num) {
var arr = num.toString().split(''), options = [];
scrambler([], arr);
function scrambler(soFar, remaining){
if(remaining.length === 0){
options.push(soFar.join(''));
}
for(var i=remaining.length ; i>0 ; i--){
var remnant = remaining.slice(0);
var n = remnant.splice(i,1);
var inSoFar = soFar.push(n[0]);
scrambler(inSoFar,remnant);
}
}
return options;
}
```

CommieKazie
posted this question on 10/29/14 **|**

3

I think the var inSoFar will cause weird behavior. You're setting it to SoFar.push(n[0]). What do you really want it to be? soFar[0]? n[0]?

mattlarsh

answered on 10/31/14

0

Thank you! That was the problem.
Also, I was modifying the same soFar variable through each recurssion. I had to turn insofar into a slice of soFar, and then push onto that.
Thank you very much!

CommieKazie

answered on 10/31/14

Log in to write an answer.