Skip to content

Instantly share code, notes, and snippets.

@JackHowa
Created April 18, 2019 16:48
Show Gist options
  • Save JackHowa/91a0fd494bdf30d800f9772070b0622e to your computer and use it in GitHub Desktop.
Save JackHowa/91a0fd494bdf30d800f9772070b0622e to your computer and use it in GitHub Desktop.
Solution for counting number of lines to anagrams in a list, done recursively
'use strict';
/**
* Count the number of anagrams in a list of words.
*
* An anagram is a word made up of the same letters as another word in the array (but not
* necessarily in the same order).
*
* I like to think of it like this: Draw a line connecting each pair of words that contain exactly
* the same letters. For example, with this list of words:
*
* TAR RAT BOB ART
*
* You would end up with 3 connecting lines (TAR---RAT, TAR---ART, RAT---ART). So the result is 3.
*
* @param {string[]} wordsList - The list of words
*
* @return {number} The number of words which are anagrams of other words
*/
const isAnagram = (a, b) => a.length === b.length
&& a
.toLowerCase()
.split('')
.every(character => b.toLowerCase().includes(character));
const countAnagrams = (wordsList) => {
// base case
if (wordsList.length < 2) {
return 0;
}
const lastElement = wordsList.pop();
let lineCount = 0;
for (let i = 0; i < wordsList.length; i++) {
if (isAnagram(lastElement, wordsList[i])) {
lineCount++;
}
}
return lineCount + countAnagrams(wordsList);
};
// helper tests
// console.log('true:', isAnagram('Pot', 'Top'));
// console.log('false:', isAnagram('Foo', 'Tom'));
console.log('Zero:', countAnagrams([]));
console.log('Zero:', countAnagrams(['Top']));
console.log('Zero:', countAnagrams(['Top', 'Spot']));
console.log('One:', countAnagrams(['Top', 'Pot']));
console.log('Two:', countAnagrams(['Top', 'Pot', 'Spot', 'Stop', 'Foo']));
console.log('Three:', countAnagrams(['Top', 'Pot', 'Opt']));
console.log(
'Nine:',
countAnagrams(['Top', 'Pot', 'Opt', 'Spot', 'Stop', 'Tops', 'Opts']),
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment