Last active
July 18, 2019 15:01
-
-
Save figloalds/e59185f4ddc925d8644565748751a209 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const getAnagrams = (str) => { | |
if(str.length === 1) { | |
return [str]; | |
} | |
let anagrams = []; | |
for(let i = 0; i < str.length; i++) { | |
let newStr = Array.from(str).filter(Boolean); | |
let thisChar = newStr.splice(i, 1); | |
newStr = newStr.join(''); | |
const subAnagrams = getAnagrams(newStr); | |
subAnagrams.forEach(anagram=> { | |
anagrams.push(thisChar + anagram); | |
}) | |
} | |
return Array.from(new Set(anagrams)); | |
}; | |
// getAnagrams('1211') | |
// -> [ '1211', '1121', '1112', '2111' ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment