简体   繁体   English

将Jumbled Array与字符串匹配的功能

[英]Function for Matching Jumbled Array to string

Does anyone know how I can match an array of jumbled letters to a word, for example, some function that will match an array eg ["a","c","a","e","c"]; 有谁知道如何将一组混乱的字母与一个单词相匹配,例如,某些与数组相匹配的函数,例如[“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. 到一个单词“ace”并给我1或如果不是-1像indexOf或InArray但是对于一个混乱的单词。 I've made a js fiddle with an example it is well documented 我做了一个js小提琴,其中有一个例子,它有很好的记录

just a note, I'll be comparing the array of letters to anywhere from 30000 - 50000 words. 只是一个注释,我将比较字母数组到30000 - 50000字。

https://jsfiddle.net/AlexanderMitrakis/89dchpt8/1/ 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)
               */

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM