简体   繁体   中英

Converting from Java to Javascript, integer math issues

For an assignment I have to create a sudoku board in JavaScript. I had the code in Java so I attempted to convert it, but the code for checking 3x3s utilizes Integer math, which broke the code in javascript. I don't have a whole lot of experience with Javascript and could use some help figuring this out.

We've been able to set up an array to hold boolean values that check the numbers found in a 3x3, but the problem seems to be within the for loops. They're used to jump from 3x3 to 3x3 without checking the wrong spot. However the java int math throws it for a bit of a loop.

function checkBlocks(board) {
   //check each 3*3 matrix

   for (var block = 0; block < 9; block++) {
    var m = [false,false,false,false,false,false,false,false,false];
        for (var i = block / 3 * 3; i < block / 3 * 3 + 3; i++) {
         for (var j = block % 3 * 3; j < block % 3 * 3 + 3; j++) {
       if (m[(board[i][j] - 1)]) {
        return false;
       }
       m[(board[i][j] - 1)] = true;
      }
     }
   }
   return true;
}

We expected it to check every 3x3, and only 3x3s, however, the math goes into decimals and becomes redundant. We just don't really know what to try. None of what we've found online has helped.

There is no specific type for integers in JavaScript. It has only one number type - Number that is double-precision 64 bit floating-point type. Therefore there is no integer division. So you need to remove fractional part using Math.floor explicitly:

function checkBlocks(board) {
   //check each 3*3 matrix

   for (var block = 0; block < 9; block++) {
    var m = [false,false,false,false,false,false,false,false,false];
        for (var i = Math.floor(block / 3) * 3; i < Math.floor(block / 3) * 3 + 3; i++) {
         for (var j = block % 3 * 3; j < block % 3 * 3 + 3; j++) {
       if (m[(board[i][j] - 1)]) {
        return false;
       }
       m[(board[i][j] - 1)] = true;
      }
     }
   }
   return true;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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