雖然這是一個老問題,但我希望我的回答可以幫助某人。
在一個井字棋項目上工作時,我試圖推廣一個解決方案,我認爲它也可以解決您的問題。 此實現將尋找「行模式」(這意味着它僅適用於元素的序列上的水平/垂直/對角線。
function lookForCombinationsOnGrid(grid, ...args) {
/* This function looks for a linear sequence of elements (x, o, undefined)
on the grid.
It returns an array of all beginning and ending coordinates (x, y) for
the corresponding pattern.
Inputs:
- grid, a system of coordinates with an x-axis and an inverted y-axis.
- elements can be any sort of built-in objects.
*/
let sequence = [];
sequence.push(args[0]);
args.reduce(function (accumulator, currentValue, currentIndex, args) {
return sequence.push(currentValue);
});
console.log("sequence =", sequence);
let testedArr;
// Look for this combination horizontally.
let result1 = [];
for (i = 0; i < grid.length; i++) {
for (j = 0; j <= grid[i].length - sequence.length; j++) {
testedArr = [];
for (k = 0; k < sequence.length; k++) {
testedArr.push(grid[i][j + k]);
}
if (testedArr.join() === sequence.join()) {
let start = [j, i];
let end = [j + sequence.length - 1, i];
result1.push([start, end]);
}
}
}
console.log("Found", result1.length, "results horizontally. ");
// Look for this combination vertically.
let result2 = [];
for (i = 0; i < grid[0].length; i++) {
for (j = 0; j <= grid.length - sequence.length; j++) {
testedArr = [];
for (k = 0; k < sequence.length; k++) {
testedArr.push(grid[j + k][i]);
}
if (testedArr.join() === sequence.join()) {
let start = [i, j];
let end = [i, j + sequence.length - 1];
result2.push([start, end]);
}
}
}
console.log("Found", result2.length, "results vertically. ");
// Look for this combination diagonally.
let result3 = [];
for (i = 0; i <= grid.length - sequence.length; i++) {
for (j = 0; j <= grid[i].length - sequence.length; j++) {
testedArr = [];
for (k = 0; k < sequence.length; k++) {
testedArr.push(grid[i + k][j + k]);
}
if (testedArr.join() === sequence.join()) {
let start = [j, i];
let end = [j + sequence.length - 1, i + sequence.length - 1];
result3.push([start, end]);
}
}
}
console.log("Found", result3.length, "results diagonally (left to right). ");
// and diagonally the other way...
let result4 = [];
for (i = 0; i <= grid.length - sequence.length; i++) { // line i = 0
for (j = grid[i].length-1 ; j >= 0 + sequence.length-1; j--) { // column j = 1
testedArr = [];
for (k = 0; k < sequence.length; k++) {
testedArr.push(grid[i + k][j - k]); // + 1 line to i, -1 col to j
}
if (testedArr.join() === sequence.join()) {
let start = [j, i];
let end = [j - sequence.length + 1, i + sequence.length - 1];
result4.push([start, end]);
}
}
}
console.log("Found", result4.length, "results diagonally (right to left). ");
let result = result1.concat(result2);
result = result.concat(result3);
result = result.concat(result4);
return result;
}
grid = [[1, 1, 3],
[1, 1, 1],
[1, 1, 1],
[0, 1, 1]];
console.log(lookForCombinationsOnGrid(grid, 1, 1, 1, 0));
我希望這可以幫助別人。
而你的問題是...? –
您的算法是否必須找到所有?或者只有一個?例如:在您的最後一個矩陣中是否應該找到全部3? – corsiKa
是否每個位置都是相同的數字 - 您永遠不需要匹配,例如, [1 2 3]? –