No repeats please

In this example below you will see how to do a No repeats please with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by DanRom624, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright DanRom624 ©
  • HTML
  • CSS
  • JavaScript
    

/*Downloaded from https://www.codeseek.co/DanRom624/no-repeats-please-JXVzWZ */
    


/*Downloaded from https://www.codeseek.co/DanRom624/no-repeats-please-JXVzWZ */
    //To swap two given elements of the array
var swap = function(array, pos1, pos2) {
  var temp = array[pos1];
  array[pos1] = array[pos2];
  array[pos2] = temp;
};

//Finds premutation applying the Heap's Algorithm 
var heapPerm = function(array, output, n) {
  var j = 0;
  n = n || array.length;
  if (n === 1) {
    output(array);
  } else {
    for (var i = 1; i <= n; i++) {
      heapPerm(array, output, n - 1);
      if (n % 2) {
        j = 1;
      } else {
        j = i;
      }
      swap(array, j - 1, n - 1);
    }
  }
};

function permAlone(str) {

  console.log("str", str);
  var givenArray = str.split('');
  console.log("givenArray", givenArray);
  var newArray = [];

  heapPerm(givenArray, function(input) {
    var tempStr = input.join('');
    newArray.push(tempStr);
  });
  console.log("Fin.", newArray);

  // Filters the array of permutations, to exclude those with repeats
  var expression = /(.)\1+/g;
  var filteredArr = newArray.filter(function(val) {
    return !val.match(expression);
  });
  console.log("filteredArr", filteredArr);

  return newArray;
}

permAlone('aab');

/*
Return the number of total permutations of the provided string that don't have repeated consecutive letters. Assume that all characters in the provided string are each unique.

For example, aab should return 2 because it has 6 total permutations (aab, aab, aba, aba, baa, baa), but only 2 of them (aba and aba) don't have the same letter (in this case a) repeating.

Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code.

Here are some helpful links:

    Permutations

    RegExp
*/

Comments