I have a list of all the words in the English dictionary (270,000 words) stored in a variable called theList . I have a scrambled word word that I want to decrypt by matching it with a list of words. Initially, I thought the following code would do the trick, but it doesn't work so well.
var theList; // Contains all the words in the English dictionary. var word = "iexospensr"; // The word I want to unscramble. var matches = word.match(new RegExp("^["+word+"]{"+word.length+"}$", "gim"));
I would expect "EXPRESSION" as a result without decryption, but instead I get much more results (see below).
EERINESSES,EXPRESSERS,EXPRESSION,IRONNESSES,ISOSPORIES,NONPERSONS,NONPROSSES,NOSINESSES,OPENNESSES,OPPRESSION,OPPRESSORS,ORNERINESS,PENSIEROSO,PENSIONEER,PENSIONERS,PEPPERONIS,PERSIENNES,PERSONISES,PIPINESSES,PIXINESSES,POORNESSES,PORINESSES,POSSESSION,POSSESSORS,PREEXPOSES,PREPOSSESS,PREPPINESS,PRESENSION,PRIORESSES,PRISSINESS,PROPENSION,PROPERNESS,REINSPIRES,REPRESSERS,REPRESSION,REPRESSORS,RESERPINES,RESPONSERS,RESPONSORS,RIPENESSES,ROPINESSES,ROSINESSES,SERENENESS,SEXINESSES,SIXPENNIES,SNIPPINESS,SORENESSES,SPINNERIES
Perhaps if I could find a way to tell the regular expression to examine each letter in the word string only once, regardless of the order of the letters. Thus, the end result will be an array of combinations of these letters, not permutations (which I have now).
Any help would be appreciated.
EDIT: I think the way is: 1. find all combinations of the scrambled word 2. match them with a list of words for validation
If you have a better solution (in terms of performance), this will help.
The best solution to this problem is to reorder the anagram alphabetically and the entire list of words and match the word with each item in the list.
Here is the code:
var textList; // the entire dictionary var list = textList.match(/^.*$/gim); var sortedList = []; list.forEach(function(element, index, array) { sortedList[index] = element.split("").sort().join(""); }); function unscramble(word) { word = word.toUpperCase().split("").sort().join(""); var matches = []; for (var i = 0; i < list.length; i++) { if (word.indexOf(sortedList[i]) >= 0) { if (!matches[list[i].length]) matches[list[i].length] = []; matches[list[i].length].push(list[i]); } } return matches; }