gpt4 book ai didi

javascript - 如何动态查找数独子框值

转载 作者:行者123 更新时间:2023-11-28 04:03:43 25 4
gpt4 key购买 nike

我正在尝试制定一种算法来动态检查常规数独网格是否已解决。我有一个硬编码的解决方案,通过使用框内所需值的坐标来获取每个子框的值。但是,我似乎无法弄清楚如何编写一个函数,仅通过查看数独矩阵的大小以及我想要的盒子,它就会输出该盒子部分内的值。

我的代码:

const sudoku = [
[1, 2, 3, 4],
[3, 4, 1, 2],
[2, 3, 4, 1],
[4, 1, 2, 3]
]

class SudokuChecker {

getCheckList (length) {
const nums = {}
for (let i=1; i<=length; i++) nums[i] = 0
return nums
}

isCorrect (list) {
const checkList = this.getCheckList(list.length)
list.forEach(num => checkList[num]++)
return Object.values(checkList).every(x => x == 1)
}

getRow (matrix, row) {
return matrix[row]
}

getColumn (matrix, col) {
return matrix.map(row => row[col])
}

getBox (matrix, box) {
const procNum = Math.sqrt(matrix.length)
// given some box ID number (starting at 0), all I need :
// a) index of that box's top row
const topRow = 'find_me' // calculated with "box" and procNum somehow...
// b) the index of that box's first num at that row.
const sliceFrom = 'find_me' // no idea at the moment how to calculate...
let boxNums = []
for (let i=0; i<procNum; i++) {
boxNums = boxNums.concat(matrix[topRow + i].slice(sliceFrom, sliceFrom + procNum))
}
return boxNums
}

checkLists (matrix, type, unit=0) {
const pass = this.isCorrect(this['get'+type](matrix, unit))
if (!pass) return false
if (unit == matrix.length-1) return pass
return this.checkLists(matrix, type, ++unit)
}

checkAll (matrix) {
const types = ['Row', 'Column', 'Box']
return types.map(t => this.checkLists(matrix, t)).every(x => x === true)
}

}

最佳答案

我在 friend 的帮助下得到的答案:

getBox (matrix, box) {
const procNum = Math.sqrt(matrix.length)
const topRow = Math.floor(box/procNum) * procNum
const sliceFrom = (box % procNum) * procNum
let boxNums = []
for (let i=0; i<procNum; i++) {
boxNums = boxNums.concat(matrix[topRow + i].slice(sliceFrom, sliceFrom + procNum))
}
return boxNums
}

关于javascript - 如何动态查找数独子框值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46878160/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com