Files
30-seconds-of-code/snippets/anagrams-of-string-(with-duplicates).md
Angelos Chalaris f40115ff3b Swap, anagrams, occurences
Fixed sorting title for strings.
2017-12-06 23:50:23 +02:00

17 lines
563 B
Markdown

### 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`.
```js
var 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;
}, []);
}
```