繁体   English   中英

想在 allRowsValid 中使用 getRow 作为数独求解器,我该如何解决?

[英]want to use getRow inside allRowsValid for sudoku solver how can i solve it?

所以我一直在尝试编写一个数独求解器,我不得不在扩展 class 中完成方法,这是代码的开头:

class Board extends EventEmitter {
  constructor(board) {
    super();

    this.board = board || [
      [0, 0, 0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 0, 0],
    ];
  }

  getRow(index) {
    return this.board[index];
  }

在这里我必须检查该板内的所有行是否有效(从 1 到 9 不重复):

allrowsValid() {
  for (let c = 0; c < 9; ++c) {
    **var row = this.getRow(c)** ***//what i need to fix***

      for ( let num = 1; num <= 9; ++num){
        if (this.board[row][c] === num) {
          return false;
      }
      }
    }
    return true;
    }

我该如何解决? 谢谢 !

这取决于“有效”是指“满屋”([1-9] 范围内的所有数字),还是无效([1-9] 范围内的某些数字没有重复)。 过去我在数独中使用位算术来专门解决这个问题:

// class methods...

validHouse( array) {
    // no non zero repetitions
    let allowed = 0b1111111110;
    for( let index = 9; index--;) {
        if( array[index]) {
            let position  = 1 << array[index];
            if( !(allowed & position)) {
                 return false; // repetition
            }
            allowed &= ~position;
        }
    }
    return true;
}

fullHouse(array) {
    // all house numbers completed
    let required = 0b1111111110;
    for( let index = 9; index--;) {
        if( array[index]) {
            let position  = 1 << array[index];
            required &= ~position;
        }
    }
    return required == 0;
}

因此,如果您想知道所有行是否完整或有效,您可以使用

allRowsFull() {
    return this.board.every(row => this.fullHouse(row));
}

allRowsValid() {
   return this.board.every(row => this.validHouse(row));
}

这里的要点不是要您使用二进制算术(这是一种后天习得的品味1 ),而是要指出一行只是需要考虑的三种数独屋子类型(行、列和框)中的一种。


1答案更新为在位清除操作中使用按位补码运算符 ( ~ ) 而不是逻辑非运算符 ( ! )。 它们不可互换。

if (this.board[row][c] === num)

问题出在这一行,您正试图通过使用该行来获取该行。 row变量已经在引用该行。

所以解决方案是将this.board[row][c]替换为row[c]

for ( let num = 1; num <= 9; ++num){
    if (row[c] === num) {
        return false;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM