-4

So If a have A, B, C , I want to create some strings whith length 4

so the output will be

AAAA
AAAB
AAAC
AABA
AABB
AABC
ABAB
....
CCCC
DarkBee
  • 16,592
  • 6
  • 46
  • 58
elti musa
  • 710
  • 2
  • 7
  • 14
  • Linked duplicate question is not duplicate. In linked question only unique character combinations allowed, in this question duplicates of same character is allowed. – Artem P Feb 24 '21 at 10:19

1 Answers1

-1

There are some comments, so you can understand this. Thanks to http://www.walmik.com/2013/03/rearrange-letters-of-a-word/

function permutate(theWord){

      //Array to store the generated words
      var words = [];

      /**
       * Recursive function to split a string and rearrange 
       * it's characters and then join the results
       */
      function rearrange(str, prefix) {

        var i, singleChar, balanceStr, word;

        //The first time round, prefix will be empty
        prefix = prefix || '';

        //Loop over the str to separate each single character

        for(i = 0; i < str.length; i++) {
          singleChar = str[i];
          balanceStr = str.slice(0, i) + str.slice(i+1);

          //join the prefix with each of the combinations
          word = prefix + singleChar + balanceStr;

          //Inject this word only if it does not exist
          if(words.indexOf(word) < 0) words.push(word);

          //Recursively call this function in case there are balance characters
          if(balanceStr.length > 1) rearrange(balanceStr, prefix + singleChar);

        }

      }

      //kick start recursion
      rearrange(theWord);
      return words;

    }

    var permutatedWord = permutate('goal');
    console.log(permutatedWords);
AngularLover
  • 364
  • 1
  • 12