Since I’ve been trying on my own for way too long I decided to finally take a hint. I saw here that I could solve it recursively (which had crossed my mind before, when I was trying on my own, so I thought I’d implement that one). I’m trying to implement the provided pseudocode but I’m a bit stuck.
var str = ???;
permAlone(current position in original string, characters used already in original string, created string) {
if (current string is finished) {
print current string;
} else {
for (var i = 0; i < str.length; i++) {
if (str[i] has not been used) {
put str[i] into the current position of new string;
mark str[i] as used;
permAlone(current position in original string, characters used already in original string, created string);
remove str[i] as used because another branch in the tree for i + 1 will likely use it;
}
}
}
}
permAlone(0, nothing used yet, empty new string (or array the same size as str));
My code so far is:
function permAlone(str) {
var num = 0;
var combos = [];
var c = 0;
str = str.split("");
function perms(pos,used,combo){
if(combo.length==str.length){
combos.push(combo);
}else{
for(var i=0;i<str.length;i++){
if(used.indexOf(i)==-1){
//var curr = "";
//combo = [];
//curr[pos]=str[i];
combo[pos]=str[i];
//curr.concat(str[i]);
used.push(i);
perms(pos,used,combo);
used.push(i);
}
//pos++;
}
}
}
perms(0,[],[]);
return num;
}
Specifically, I’m not sure if I use pos right and also I’m not sure if I intepret put str[i] into the current position of new string;
and remove str[i] as used because another branch in the tree for i + 1 will likely use it;
correctly. Note that the commented lines are the ones I’m not sure if I should include (by themselves or in place of other similar )or where should I put them (like pos++
). In the end I always get an empty combos array.
Am I on the right track? Are there any details I’ve missed? Any suggestions would be appreciated!