如何动态查找数独子框值

How to find Sudoku sub-box values dynamically

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

我的代码:

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)
  }

}

在朋友的帮助下得到的答案:

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
}