1
votes

First of all sorry for bothering with a question asked several times before.But I have to say that I did read through the related questions about string permutations and I could not figure out the actual problem with the code I have below. I want to return the combinations of a string.Please help me out in finding the mistake ! PS: I have just started learning javascript!

var result = [];

function doPerm(prefix, suffix, result) {
    if (suffix.length === 0)
        result.push(prefix);
    else {
        for (i = 0; i < suffix.length; i++) {
            doPerm(prefix + suffix.charAt(i), suffix.slice(0, i) + suffix.slice(i + 1), result);
        }
    }
}

function permAlone(str) {
    var prefix = "";
    var suffix = str;
    doPerm(prefix, suffix, result);
    return result;
}

   console.log(permAlone('aab'));
INPUT:'aab' OUTPUT:[aab,aab,aba,aba,baa,baa]
2
so you want to retun all combinations of aab, e.g aab, aba, baa etc - Richard Housham
@RichardHousham Yes! Exactly! - Gowtham Raj
I'll check my answer! - Richard Housham

2 Answers

1
votes

Your logic was correct actually, you just declared i without var in for loop which made it global and was giving you errors. It seems to be working once that is corrected:

var result = [];

function doPerm(prefix, suffix, result) {
if (suffix.length === 0)
    result.push(prefix);
else {
    for (var i = 0; i < suffix.length; i++) {
        doPerm(prefix + suffix.charAt(i), suffix.slice(0, i) + suffix.slice(i + 1), result);
    }
}
}

function permAlone(str) {
var prefix = "";
var suffix = str;
doPerm(prefix, suffix, result);
return result;
}

console.log(permAlone('aab'));
0
votes

This is a bit of on the back of a piece of paper thinking but.

for(i;i<string.length;i++) {
      var s = string.slice(i,i+1);
      var c = string.charAt(i);
      var q = s.split("");

      for(b=0;b<q.length;b++) {

          var newArray = q.slice();
          newArray.splice(b,0,c);
          result.push(newArray.join());
      }
}

does that work?

UPDATE this seems to work!

<script>

var string = "aab";
var result = []; 

for(i=0;i<string.length;i++) {
      var c = string.charAt(i);

      var q = string.split("");
      q.splice(i,1);

      console.log("first");
      console.log(q);
      console.log(c);

      for(b=0;b<q.length;b++) {



          var newArray = q.slice();
          newArray.splice(b,0,c);
          result.push(newArray.join());
      }
}


console.log(result);

</script>