6

Does anyone know how I can match an array of jumbled letters to a word, for example, some function that will match an array e.g ["a","c","a","e","c"]; to a word "ace" and give me 1 or if not -1 like indexOf or InArray but for a jumbled word. I've made a js fiddle with an example it is well documented

just a note, I'll be comparing the array of letters to anywhere from 30000 - 50000 words.

https://jsfiddle.net/AlexanderMitrakis/89dchpt8/1/

this.gameletters = []; //Array of Game letters. 
                //e.g. ["P", "E", "H", "E", "U", "I", "S", "Q", "N"];


this.possiblesolution = new String(); //highest solution within gameletters
                //e.g. "QUEENSHIP" (related to above letters) 

this.wordBank = new Array(); 
               //array of arrays structure is formated around alphabet with an array for each character:
               /* 
                a: Array(7295)
                b:Array(7271)
                c:Array(11381)
                d:Array(7216)
                ... 
                y:Array(607)
                z:Array(623)
               */
2
  • where do you store the dictionary of words? Commented May 22, 2017 at 3:22
  • I store it as a multi-dimensional array as this.wordBank the wordBank it is stored sorted alphabetically by characters then inside each character array is alphabetically all words within that letter this.wordBank[character][characterword] Commented May 22, 2017 at 3:25

1 Answer 1

1

A recursive strategy is a simple solution, but if your gameletters array gets too big, it will really slow down the execution. For a game like scrabble, it should be adequate though.

Fiddle

var gameletters = ["P", "E", "H", "E", "U", "I", "S", "Q", "N"];
var wordbank = {
  "a": Array(3461),
  "b": Array(2391),
  //...
};

var matches = {};

function step(word, letters) {
  for(var i = 0, len = letters.length; i < len; i++) {

    var arr = letters.map(a => a);
    if (arr.length === 0) {
      return;
    }

    var letter = arr[i];
    arr.splice(i,1);
    test(word + letter);

    if (arr.length) {
      step(word + letter, arr)
    }
  }
}

function test(word) {
  var firstLetter = word.substr(0,1);
  if (wordbank[firstLetter].indexOf(word) >= 0) {
    matches[word] = 1;
  }
}

step("", gameletters);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.