Trying to solve 'No Repeats Please'

Hey!

So I’ve been trying to solve the No Repeats Please challenge for a few hours with no success. I did watch this video (without the code section of it) and I think I’ve got a good understanding of the process of finding all permutations of a string and can do it by hand.

I was really optimistic before I’d written any code but for the life of me I can not turn it into code. Currently I’m just going straight down the “ladder” and I have no idea how to solve it in a recursive way. I can do it for only the first set of characters (which in this case is the same as the input). I don’t know how to get back up the “ladder”

Here is my code so far: (I haven’t added most of the stuff like testing for repeating characters next to each other as that’s my smallest problem right now)

function permAlone(str) {
  var sortedChars = str.split("").sort();

  //turn 'str' into an array of objects
  var charArr = sortedChars.reduce(function(acc, item) {
    acc.push({char: item, count: 1});
    return acc;
  }, []);
  
  var counter = 0;
  var result = [];
  for(var i = 0; i < charArr.length; i++) {
    for(var prop in charArr[i]) {
     if(prop == "count" && charArr[i].count > 0) {
       result.push(charArr[i].char);
       charArr[i].count--;
       if(result.length == charArr.length) {
        result = result.join("");
         counter++;
         //good. now what?
      }
     }
    }
  }
  
  return result;   //temporary; 
                   //'counter' would return 1
}

console.log(permAlone('aab'));  //returns "aab"

Am I going completely the wrong way here? The more I look at my code the less sense it makes.

Any help would be appreciated!

When writing recursive algorithms, the trick to going back up is to use the return statement. This pops execution out of the currently running function and goes back into the function that called it.

The thing that I’m noticing about your algorithm is that it won’t actually give you permutations of a string. At least, I can’t see any part of your code that changes the order of the items. I think what you’ve done here is a very good, innovative attempt, but it’s not going to give you what you are looking for. I didn’t watch the video so I’m not sure what you got from it or what the code would have shown, but I don’t think it’s cheating to give you the pseudo-code for a permutation algorithm that will help you. In fact, if you work at implementing Heap’s algorithm in JavaScript, you’ll learn a lot about how to create a recursive algorithm and get string permutations.