Skip to content

Instantly share code, notes, and snippets.

@MattGoldwater
Last active April 29, 2020 00:57
Show Gist options
  • Save MattGoldwater/15c914fc14fef48a5e2fa3c00da29e7e to your computer and use it in GitHub Desktop.
Save MattGoldwater/15c914fc14fef48a5e2fa3c00da29e7e to your computer and use it in GitHub Desktop.
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