我正在尝试编写一个Sudoku验证器,该验证器接收包含9位数字的数组,每个数字代表一个Sudoku行。
[[5, 3, 4, 6, 7, 8, 9, 1, 2],
...
[3, 4, 5, 2, 8, 6, 1, 7, 9]];
重点是获取代表列的单独数组:
[[5, ...3],
...
[2, ...9]];
这样我可以进一步验证所有行/列是否都包含唯一值,换句话说-数字不会在其中重复。
我已经尝试遍历行数组,并在每次迭代中将每行的第一位推到单独的数组中,以最后获得一个列数组。
let columns = new Array(9).fill([]),
board = [
[5, 3, 4, 6, 7, 8, 9, 1, 2],
[6, 7, 2, 1, 9, 5, 3, 4, 8],
[1, 9, 8, 3, 4, 2, 5, 6, 7],
[8, 5, 9, 7, 6, 1, 4, 2, 3],
[4, 2, 6, 8, 5, 3, 7, 9, 1],
[7, 1, 3, 9, 2, 4, 8, 5, 6],
[9, 6, 1, 5, 3, 7, 2, 8, 4],
[2, 8, 7, 4, 1, 9, 6, 3, 5],
[3, 4, 5, 2, 8, 6, 1, 7, 9]
];
for (let i = 0; columns[i].length < 9; i++) {
console.log(`While column ${i} is not filled with 9 digits`)
for (let j = 0; j < 9; j++) {
console.log(`Push ${i}-th digit of ${j} line to column ${i} `)
columns[i].push(board[j][i]);
}
}
但是我忽略了一些东西,因为我得到了一个包含9个第一列的数组。
我忽略的是:
使用.fill创建的数组是指向单个数组的链接,因此,对一个数组进行变异会使其余的变异。感谢 CertainPerformance 对此进行了澄清。
不恰当的解决方案是将列声明为:
让列= [[],[],[],[],[],[],[],[],[]];
更好的方法是声明一个空数组:
让列= [];
然后在每次迭代中在其中生成一个数组:
for (let i = 0; columns.length < 9; i++) {
columns[i] = new Array();
for (let j = 0; j < 9; j++) {
columns[i].push(board[j][i]);
}
}