我有一个数组,比方说
var array = [ [1, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 1, 0],
[0, 0, 1, 0, 1, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]
]
我想创建一个 来查找数字在对 Angular 线上出现四次的所有匹配项。
我目前正在使用
function checkDiagonal(array, bottomToTop) {
var Ylength = array.length;
var Xlength = array[0].length;
var maxLength = Math.max(Xlength, Ylength);
var temp;
var returnArray = [];
for (var k = 0; k <= 2 * (maxLength - 1); ++k) {
temp = [];
for (var y = Ylength - 1; y >= 0; --y) {
var x = k - (bottomToTop ? Ylength - y : y);
if (x >= 0 && x < Xlength) {
temp.push(array[y][x]);
}
}
if(temp.length > 0) {
returnArray.push(temp.join(''));
}
}
return returnArray;
}
然而它并不总能找到所有的解决方案
最佳答案
有趣的案例。实际上很难找到/写一个简单的方法。 我试图理解您的脚本,但发现它有点难以遵循/调试,因此尝试重现您在我自己的脚本中所做的事情并设法获得所需的结果。它的代码行比你的多,但它有一些变量和一些注释一起声明,因此更容易理解(对于其他人,在未来)。
希望对您有所帮助:
function checkDiagonal(array, matchCount) {
var result = [];
if(array.length >= matchCount) {
// Search towards bottom-right.
result = result.concat(getDiagonalResult(array, matchCount, 1));
// Search towards top-right.
result = result.concat(getDiagonalResult(array, matchCount, -1));
} else {
// No use searching if not enough rows are present.
}
return result;
}
function getDiagonalResult(array, matchCount, direction) {
var result = [];
// Specific from and to points to only search in possible rows (e.g. no use searching top-right on first row).
var yFrom, yTo;
// Search direction (bottom-right vs top-right).
switch(direction) {
// Bottom-right.
case 1:
yFrom = 0;
yTo = (array.length - matchCount);
break;
// Top-right.
case -1:
yFrom = (matchCount - 1);
yTo = (array.length - 1);
break;
}
// Loop through all 'rows'.
for(var y = yFrom; y <= yTo; y++) {
// Loop through all 'columns'.
for(var x = 0; x <= (array[y].length - matchCount); x++) {
// Current value to match on.
var originalValue = array[y][x];
var matches = [];
// Get matches.
for(var i = 0; i < matchCount; i++) {
// Search direction (row up or down).
var yDirection = (i * direction);
var value = array[y+yDirection][x+i];
if(value === originalValue) {
matches.push(value);
}
}
if(matches.length == matchCount) {
result.push(matches.join(""));
}
}
}
return result;
}
var array = [
[1, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 1, 0],
[0, 0, 1, 0, 1, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]
];
console.log(checkDiagonal(array, 4));
关于javascript - 沿对 Angular 线查找数组中的相同值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40186650/