Created
September 16, 2020 11:36
-
-
Save thiagobitencourt/918701bc65c7af7ec3b0845999822d0d to your computer and use it in GitHub Desktop.
Remove anagrams from text list
This file contains hidden or 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 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