有谁知道如何将一组混乱的字母与一个单词相匹配,例如,某些函数会匹配 一个数组,例如[“a”,“c”,“a”,“e”,“c”]; 到一个单词“ace”并给我1或如果不是-1像indexOf或InArray但是对于一个混乱的单词。 我已经做了一个js小提琴,其中有一个很好的文档
只是一个注释,我将把字母数组比作30000 - 50000字。
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)
*/
答案 0 :(得分:1)
递归策略是一个简单的解决方案,但如果你的游戏玩法数组太大,它将真正减慢执行速度。对于像拼字游戏这样的游戏,它应该足够了。
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);