我构建了一个数独网格,创建了一个多维数组。 我试图实现的一个逻辑是检查九个中心周围的数字。
var grid = [
[1,4,2,8,0,6,7,9,5],
[8,0,0,0,9,1,0,7,1],
[4,9,0,2,5,2,0,0,0],
[9,0,2,9,1,2,0,0,0],
[0,5,8,8,5,3,9,0,0],
[3,1,0,7,6,4,0,2,0],
[2,3,0,1,5,8,7,9,4],
[7,8,0,0,7,5,4,0,0],
[6,0,7,4,3,7,0,0,9],
];
我的数独网格中心如下:
var gridCenters = [grid[1][1],grid[1][4],grid[1][7],grid[4][1],grid[4][4],grid[4][7],grid[7][1],grid[7][4],grid[7][7]];
每个中心周围的9个数字(包括中心)如下:
var nineFromSquare = [grid[i][j],grid[i-1][j-1],grid[i-1][j],grid[i][j-1],grid[i+1][j+1],grid[i+1][j],grid[i+1][j],grid[i-1][j+1],grid[i+1][j-1]];
我尝试创建一个for循环,它接受每个gridCenter并将其索引应用于某个值,以便为sudoku求解添加额外的逻辑。基本上,我想检查中心周围的数字是数字还是空的。
任何提示?谢谢!
答案 0 :(得分:0)
如果电路板上的0
指定为空,则可能如下所示;
function getBorder(center){
var offsets = [[-1,-1],[0,-1],[1,-1],[1,0],[1,1],[0,1],[-1,1],[-1,0]];
return offsets.map(c => [c[0] + center[0], c[1] + center[1]]);
}
function getNestedValue(o,...a){
var val = o;
for (var prop of a) val = typeof val === "object" &&
val !== null &&
val[prop] !== void 0 ? val[prop]
: undefined;
return val;
}
var grid = [[1,4,2,8,0,6,7,9,5],
[8,0,0,0,9,1,0,7,1],
[4,9,0,2,5,2,0,0,0],
[9,0,2,9,1,2,0,0,0],
[0,5,8,8,5,3,9,0,0],
[3,1,0,7,6,4,0,2,0],
[2,3,0,1,5,8,7,9,4],
[7,8,0,0,7,5,4,0,0],
[6,0,7,4,3,7,0,0,9],
],
centers = [[1,1],[1,4],[1,7],[4,1],[4,4],[4,7],[7,1],[7,4],[7,7]];
result = centers.map(c => getBorder(c).every(b => getNestedValue(grid,...b)));
console.log(result);
getBorder()
函数返回由函数的单个参数提供的中心项周围的8个项。
getNestedValue()
函数将动态返回以正确顺序在数组中提供的对象/数组的无限嵌套属性的项。在这种情况下[x,y]
如果您不需要每个中心的结果,只需要一个结果,那么您可以转换
result = centers.map(c => getBorder(c).every(b => getNestedValue(grid,...b)));
成;
result = centers.every(c => getBorder(c).every(b => getNestedValue(grid,...b)));