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

标签 javascript dynamic-programming sudoku

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

我的代码:

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/

相关文章:

dynamic-programming - 如何解决 dfs 和 dp 中的算法问题

c++ - 当我得到数独的网格结果时如何停止递归?

python - for循环作为python中函数的输入参数

javascript - knockout : cascade write to multiple observables if no value yet?

Java 或任何其他语言 : Which method/class invoked mine?

javascript - 谷歌地图使用 lat/lng 从 ajax 成功返回的数据移动标记

java - 没有重复和顺序的动态规划/组合并不重要

javascript - 如何根据段落内的文本值更改文本颜色

c++ - 需要多个数独解决方案

javascript - 根据用户在页面中的位置显示或隐藏 HTML