Ad
Strings
Data Types
Code
Diff
  • function swap(arr, a, b) {
      let tmp = arr[a];
      arr[a] = arr[b];
      arr[b] = tmp;
      return arr;
    }
    
    function getNextShuffle(arr) {
      let n = arr.length;
      let j = n - 2;
      let l = n - 1;
      
      while (arr[j] >= arr[j + 1] && j > -1) {
        j--;
      }
      
      if (j === -1) {
        return false
      }
      
      while (arr[j] >= arr[l] && j < l) {
        l--
      }
    
      arr = swap(arr, j, l);
      arr = arr.slice(0, j + 1).concat(arr.slice(j + 1).reverse());
    
      return arr;
    }
    
    function allAnagrams(word, noRepeats) {
      let shuffle = word.split('').map((item, i) => i);
      let result = [];
      
      do {
        let anagram = shuffle.map((index) => word[index]).join('');
        if (!noRepeats || result.indexOf(anagram) < 0) {
          result.push(anagram);
        }
        shuffle = getNextShuffle(shuffle);
      } while (!!shuffle);
    
      return result
    }
    • function allAnagrams(word) {
    • function swap(arr, a, b) {
    • let tmp = arr[a];
    • arr[a] = arr[b];
    • arr[b] = tmp;
    • return arr;
    • }
    • if (word.length < 2) {
    • return [word];
    • } else {
    • var allAnswers = [];
    • for(var i = 0; i < word.length; i++) {
    • var letter = word[i];
    • var shorterWord = word.substr(0, i) + word.substr(i+1, word.length - 1);
    • var shortWordArray = allAnagrams(shorterWord);
    • for (var j = 0; j < shortWordArray.length; j++) {
    • allAnswers.push(letter + shortWordArray[j]);
    • }
    • }
    • return allAnswers;
    • }
    • function getNextShuffle(arr) {
    • let n = arr.length;
    • let j = n - 2;
    • let l = n - 1;
    • while (arr[j] >= arr[j + 1] && j > -1) {
    • j--;
    • }
    • if (j === -1) {
    • return false
    • }
    • while (arr[j] >= arr[l] && j < l) {
    • l--
    • }
    • arr = swap(arr, j, l);
    • arr = arr.slice(0, j + 1).concat(arr.slice(j + 1).reverse());
    • return arr;
    • }
    • function allAnagrams(word, noRepeats) {
    • let shuffle = word.split('').map((item, i) => i);
    • let result = [];
    • do {
    • let anagram = shuffle.map((index) => word[index]).join('');
    • if (!noRepeats || result.indexOf(anagram) < 0) {
    • result.push(anagram);
    • }
    • shuffle = getNextShuffle(shuffle);
    • } while (!!shuffle);
    • return result
    • }