Skip to content

Instantly share code, notes, and snippets.

@azer
Created July 27, 2012 19:25
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 azer/3190011 to your computer and use it in GitHub Desktop.
Save azer/3190011 to your computer and use it in GitHub Desktop.
var words = "orman roman tilki kilit iri kirli kuzu at rahat karat tarak".replace(/[^\w\s]+/g,'').split(" "),
dict = createDict(words);
console.log( 1, anagrams("tikil") ); // tilki, kilit
console.log( 2, anagrams("atkr") ); // karat, tarak
console.log( 3, anagrams("armon") ); // roman, orman
function createDict(list){
var i = words.length,
el, result = {};
while( i -- ){
el = sort(words[i]);
! result[el] && ( result[el] = [] );
result[el].push( words[i] );
}
return result;
}
function sort(word){
return word.split('')
.filter(function(el, ind, list){
return list.indexOf(el, ind+1) == -1;
})
.sort(function(a, b){ return a > b; }).join('');
}
function anagrams( word ){
var letters = sort(word).split(""),
result = "";
while( letters.length > 2 ){
result = letters.join("");
if( dict[ result ] ){
return dict[result];
}
letters.pop();
}
return undefined;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment