17 lines
563 B
Markdown
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;
|
|
}, []);
|
|
}
|
|
```
|