Swap, anagrams, occurences
Fixed sorting title for strings.
This commit is contained in:
16
snippets/anagrams-of-string-(with-duplicates).md
Normal file
16
snippets/anagrams-of-string-(with-duplicates).md
Normal file
@ -0,0 +1,16 @@
|
||||
### 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;
|
||||
}, []);
|
||||
}
|
||||
```
|
||||
Reference in New Issue
Block a user