Skip to content

Instantly share code, notes, and snippets.

@javier-rivera-deel
Created March 3, 2021 22:45
Show Gist options
  • Select an option

  • Save javier-rivera-deel/382cd18adf7c370d479794a89a731d3f to your computer and use it in GitHub Desktop.

Select an option

Save javier-rivera-deel/382cd18adf7c370d479794a89a731d3f to your computer and use it in GitHub Desktop.
// Installed npm packages: jquery underscore request express
// jade shelljs passport http sys lodash async mocha chai sinon
// sinon-chai moment connect validator restify ejs ws co when
// helmet wrench brain mustache should backbone forever debug jsdom
/*
Given a list of Strings, return a Set of Sets, each of which contains all strings which are anagrams of each other.
Example:
input = ['cats', 'redraw', 'tap', 'dog', 'pat', 'acts', 'drawer',
'remote', 'reward', 'god']
Output = Set {
Set {'cats', 'acts'},
Set {'redraw', 'drawer', 'reward'},
Set {'tap','pat'},
Set {'dog','god'},
Set {'remote'}
}
sjlavena@neginet.com
*/
let input = ['cats', 'redraw', 'tap', 'dog', 'pat', 'acts', 'drawer',
'remote', 'reward', 'god'];
function anagramaBuilder(list) {
// new set
let mainSet = new Set();
// iterate for every word on the list
for(let i=0;i<list.length;i++) {
// create a subset to add later to the main set
let subset = new Set();
// always add the word in revision
subset.add(list[i]);
// iterate for the rest of the array, starting on the next word
for(let j=i+1; j<list.length; j++) {
// call the anagram checker with the current word, and the next words
if(esAnagram(list[i],list[j])){
// if the word is an anagram, push it the array
subset.add(list[j]);
// take that word out of the array
list.splice(j,1);
}
}
// add the anagrams subset to the main set
mainSet.add(subset)
}
return mainSet;
}
let setOfAnagrams = anagramaBuilder(input);
console.log("---- The Set of anagrams are: -----");
console.log(setOfAnagrams);
function esAnagram(palabra, anagrama) {
if(palabra.length !== anagrama.length) return false;
let map = {};
for(let caracter of palabra) {
map[caracter] = (map[caracter] || 0 ) + 1;
}
for(let caracter of anagrama) {
if(!map[caracter]) return false;
palabra[caracter]--
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment