Files
30-seconds-of-code/snippets/anagrams-of-string-(with-duplicates).md
Angelos Chalaris 43f8529cb9 Added samples
2017-12-12 17:50:08 +02:00

625 B

Anagrams of string (with duplicates)

Use recursion. For each letter in the given string, create all the partial anagrams for the rest of its letters. Use map() to combine the letter with each partial anagram, then reduce() to combine all anagrams in one array. Base cases are for string length equal to 2 or 1.

const anagrams = s => {
  if(s.length <= 2)  return s.length === 2 ? [s, s[1] + s[0]] : [s];
  return s.split('').reduce( (a,l,i) => {
    anagrams(s.slice(0,i) + s.slice(i+1)).map( v => a.push(l+v) );
    return a;
  }, []);
}
// anagrams('abc') -> ['abc','acb','bac','bca','cab','cba']