Created
July 27, 2012 19:25
-
-
Save azer/3190011 to your computer and use it in GitHub Desktop.
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
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