Skip to content

Instantly share code, notes, and snippets.

@romerobrjp
Created August 2, 2020 13:00
Show Gist options
  • Save romerobrjp/29fc73b1baeaf818fd12a168e94202f4 to your computer and use it in GitHub Desktop.
Save romerobrjp/29fc73b1baeaf818fd12a168e94202f4 to your computer and use it in GitHub Desktop.
Fun with Anagrams
/**
*
*** Fun with Anagrams ***
*
* Given an array of strings, remove each string that is an anagram of an earlier string, then return the remaining array in sorted order.
* Example
* str = ['code', 'doce', 'ecod', 'framer', 'frame']
*
* 'code' and 'doce' are anagrams. Remove 'doce' from the array and keep the first occurrence 'code' in the array.
* 'code' and 'ecod' are anagrams. Remove 'ecod' from the array and keep the first occurrence 'code' in the array.
* 'code' and 'framer' are not anagrams. Keep both strings in the array.
* 'framer' and 'frame' are not anagrams due to the extra 'r' in 'framer'. Keep both strings in the array.
* Order the remaining strings in ascending order: ['code','frame','framer'].
*
**/
/*
* Complete the 'funWithAnagrams' function below.
*
* The function is expected to return a STRING_ARRAY.
* The function accepts STRING_ARRAY text as parameter.
*/
function funWithAnagrams(text) {
let result = text;
let counter = 0;
do {
let current = counter;
let next = current + 1;
if (isAnagram(result[current], result[next])) {
result.splice(next, 1);
counter > 0 ? counter-- : counter;
} else {
counter ++;
}
} while (counter < result.length)
return result.sort();
}
const isAnagram = (str1, str2) => {
return !!str1 && !!str2
&& str1.length === str2.length
&& str1.split('').sort().join('') === str2.split('').sort().join('');
}
function main() {
let text = ['code', 'doce', 'ecod', 'framer', 'frame'];
const result = funWithAnagrams(text);
console.log(result);
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment