Last active
April 29, 2020 00:57
-
-
Save MattGoldwater/15c914fc14fef48a5e2fa3c00da29e7e 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
function checkAnagram({word1, word2, anagramMap, alreadyInMap}) { | |
let isAnagram = true; | |
if (word2.length === word1.length) { | |
for (let j = 0; j < word2.length; j++) { | |
let current = word2[j]; | |
if (word1.indexOf(current) === -1) { | |
isAnagram = false; | |
break; | |
} | |
} | |
if (isAnagram) { | |
alreadyInMap.add(word2); | |
if (Array.isArray(anagramMap[word1])) { | |
anagramMap[word1].push(word2); | |
} else { | |
anagramMap[word1] = [word1, word2]; | |
} | |
} | |
} | |
} | |
function anagrams(words) { | |
const anagramMap = {}; | |
const alreadyInMap = new Set(); | |
words.forEach((word1, i) => { | |
if (!alreadyInMap.has(word1)) { | |
words.forEach((word2, index) => { | |
if (i !== index) { | |
checkAnagram({word1, word2, anagramMap, alreadyInMap}); | |
} | |
}) | |
} | |
}) | |
const arrFirstItems = [] | |
for (let item in anagramMap) { | |
anagramMap[item].sort(); | |
arrFirstItems.push({value: anagramMap[item][0], key: item}); | |
} | |
arrFirstItems.sort((a,b) => { | |
if (a.value < b.value) { | |
return -1; | |
}; | |
}) | |
let resultsArr = []; | |
for (let i = 0; i < arrFirstItems.length; i++) { | |
resultsArr = resultsArr.concat(anagramMap[arrFirstItems[i].key]) | |
} | |
return resultsArr; | |
} | |
const wordArray = ['reap', 'soil', 'hams', 'team', 'oils', 'meat', 'pear', 'mash']; | |
console.log(anagrams(wordArray)); /* [ | |
'hams', 'mash', | |
'meat', 'team', | |
'oils', 'soil', | |
'pear', 'reap' | |
] */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment