and*_*lrc 5 javascript arrays sub-array
好的,考虑一下:
我有一个包含一个大阵arrays,-1,a和b.
-1字段为空的意思是:
var board = [
[-1,-1, a],
[-1,-1, b],
[ b,-1, a]
]
Run Code Online (Sandbox Code Playgroud)
现在我想再次检查更小的阵列:
var solutions = [
[
[1, 1, 1]
],
[
[1],
[1],
[1]
],
[
[1],
[0,1],
[0,0,1]
],
[
[0,0,1],
[0,1],
[1]
]
]
Run Code Online (Sandbox Code Playgroud)
查看一个现有值是否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...
}
}
}
Run Code Online (Sandbox Code Playgroud)
在这个例子中,我使用了tic-tac-toe.
但我可以做任何事情.
非常有趣的问题。+1 :) 这是我对此的看法。
检查我的小提琴http://jsfiddle.net/BuddhiP/J9bLC/以获得完整的解决方案。我将尝试解释这里的要点。
我从这样的一块板开始。我使用 0 而不是 -1,因为它更容易。
var a = 'a', b = 'b';
var board = [
[a, 0, a],
[b, b, b],
[a, 0, a]
];
Run Code Online (Sandbox Code Playgroud)
我的策略很简单。
这是三个获胜案例。
首先,我创建了一个函数,它可以接受一组行(例如:[a,0,b]),并检查整行是否包含相同的值,以及该值是否不为零(或者在您的情况下为-1)。
checkForWinner = function () {
lines = Array.prototype.slice.call(arguments);
// Find compact all rows to unique values.
var x = _.map(lines, function (l) {
return _.uniq(l);
});
// Find the rows where all threee fields contained the same value.
var y = _.filter(x, function (cl) {
return (cl.length == 1 && cl[0] !== 0);
});
var w = (y.length > 0) ? y[0] : null;
return w;
};
Run Code Online (Sandbox Code Playgroud)
在这里,我连续取唯一值,如果我只能找到一个不为零的唯一值,那么他就是获胜者。
如果行中没有获胜者,我就会检查列。为了重用我的代码,我使用 _.zip() 方法将列转换为行,然后使用上面相同的函数来检查我们是否有获胜者。
var board2 = _.zip.apply(this, board);
winner = checkForWinner.apply(this, board2);
Run Code Online (Sandbox Code Playgroud)
如果我仍然没有找到赢家,那么就该检查对角线了。我编写了这个函数来从棋盘中提取两条对角线作为两行,并使用相同的 checkForWinner 函数来查看对角线是否由任何玩家主导。
extractDiagonals = function (b) {
var d1 = _.map(b, function (line, index) {
return line[index];
});
var d2 = _.map(b, function (line, index) {
return line[line.length - index - 1];
});
return [d1, d2];
};
Run Code Online (Sandbox Code Playgroud)
最后,这是我实际检查董事会获胜者的地方:
// Check rows
winner = checkForWinner.apply(this, board);
if (!winner) {
var board2 = _.zip.apply(this, board);
// Check columns, now in rows
winner = checkForWinner.apply(this, board2);
if (!winner) {
var diags = extractDiagonals(board);
// Check for the diagonals now in two rows.
winner = checkForWinner.apply(this, diags);
}
}
Run Code Online (Sandbox Code Playgroud)
如果有人想知道为什么我使用 apply() 方法而不是直接调用该函数,原因是 apply() 允许您将数组元素作为参数列表传递给函数。
我相信这也适用于 4x4 或更高的矩阵,尽管我没有测试它们。
我几乎没有时间测试该解决方案,因此如果您发现任何错误,请告诉我。