Skip to content

Instantly share code, notes, and snippets.

@thiagobitencourt
Created September 16, 2020 11:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thiagobitencourt/918701bc65c7af7ec3b0845999822d0d to your computer and use it in GitHub Desktop.
Save thiagobitencourt/918701bc65c7af7ec3b0845999822d0d to your computer and use it in GitHub Desktop.
Remove anagrams from text list
function anagrams(textList) {
const anagramList = [];
const foundAnagrams = [];
for (let i = 0; i < textList.length - 1; i++) {
const baseStr = textList[i];
if (!foundAnagrams.includes(baseStr)) {
const anagramsOnly = getAnagrams(baseStr, textList.slice(i + 1));
foundAnagrams.push(...anagramsOnly);
if (anagramsOnly.length) {
anagramList.push(baseStr);
}
}
}
return anagramList;
}
function getAnagrams(baseStr, textList) {
return textList.filter(str => isAnagram(baseStr, str));
}
function isAnagram(baseStr, compareStr) {
if (isSameSize(baseStr, compareStr)) {
const str1 = baseStr.split('').sort().join('');
const str2 = compareStr.split('').sort().join('');
return str1.indexOf(str2) === 0;
}
return false;
}
function isSameSize(str1, str2) {
return str1.length === str2.length;
}
const text = [
'code',
'doce',
'ecod',
'framer',
'frame',
'agian',
'nagai',
'rafem',
'farme',
'mefra',
'again',
];
console.log(anagrams(text));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment