好的,考虑一下:
我有一个包含数组
、-1
、a
和b
的大数组。
-1
表示该字段为空:
var board = [
[-1,-1, a],
[-1,-1, b],
[ b,-1, a]
]
现在我想再次检查较小的数组:
var solutions = [
[
[1, 1, 1]
],
[
[1],
[1],
[1]
],
[
[1],
[0,1],
[0,0,1]
],
[
[0,0,1],
[0,1],
[1]
]
]
查看 board
中的一个现有值是否与 solutions
中的模式匹配。
a
是否匹配任何模式?
b
是否匹配任何模式?
你们有没有比疯狂嵌套循环更好的方法:
var q,w,e,r,t,y;
q=w=e=r=t=y=0;
for( ; q < 3; q++ ) {
for( ; w < 3; w++ ) {
for( ; e < SOLUTIONS.length; e++ ) {
.... and so on...
}
}
}
在这个例子中,我使用了井字游戏。
但我可以是任何东西。
最佳答案
您可以做的是编译模式以提高速度。与相同语言相同的方式允许编译正则表达式以提高速度。
function compile(pattern) {
var code = "matcher = function(a) { return "
var first = null
for (var n = 0; n < pattern.length; n++) {
for (var m = 0; m < pattern[n].length; m++) {
if (pattern[n][m] == 0) continue
var nm = "["+n+"]["+m+"]"
if (first == null) {
code += "a" + nm + " != -1";
first = " && a" + nm + " == "
}
code += first + "a" + nm
}
}
code += "; }";
eval(code);
return matcher
}
那么这是在做什么呢?
例如
compile([[1],[0,1],[0,0,1]]).toString()
将创建以下函数
"function (a) { return a[0][0] != -1 && a[0][0] == a[0][0] && a[0][0] == a[1][1] && a[0][0] == a[2][2]; }"
那么如何使用呢?
要匹配您板上的位置,请按以下方式使用它
var patterns = solutions.collect(function(each) { return compile(each); })
var matches = patterns.any(function(each) { return each(board); })
注意,上面的最后一个片段假设您正在使用许多流行的高阶编程库之一,例如 lodash , 在数组原型(prototype)上提供 collect
和 any
函数,如果不使用普通的旧 for 循环代替。
关于javascript - 匹配数组中的子数组。计划中的计划,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10348877/