Last active
February 9, 2025 17:16
-
-
Save demoive/5177274 to your computer and use it in GitHub Desktop.
Validates a Sudoku game. The input (vals) is assumed to be an array of arrays with numerical values from 1 through 9.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Validates a Sudoku game. | |
* The input <vals> is assumed to be an array of arrays with numerical values from 1 through 9. | |
*/ | |
function validoku(vals) { | |
var val, | |
x, y, blockX, | |
uniqRow = {}, | |
uniqCols = [{}, {}, {}, {}, {}, {}, {}, {}, {}], // this construct could be "built up" on each loop iteration, but it's done this way for clarity of example | |
uniqBlocks = [{}, {}, {}]; | |
// iterate through the rows | |
for (y = 0; y < vals.length; ++y) { | |
// reset | |
if (y % 3 === 0) { | |
uniqBlocks = [{}, {}, {}]; | |
} | |
// iterate through the columns | |
for (x = 0; x < vals[y].length; ++x) { | |
val = vals[y][x]; | |
blockX = (x / 3) | 0; // bitwise operation to ensure integer - equivalent to Math.floor() | |
// check the validity of the row so far | |
if (uniqRow[val] === true) { | |
console.log(val + " is invalid for the row at (" + x + "," + y + ")"); | |
return false; | |
} | |
uniqRow[val] = true; | |
// check the validity of the column so far | |
if (uniqCols[x][val] === true) { | |
console.log(val + " is invalid for the column at (" + x + "," + y + ")"); | |
return false; | |
} | |
uniqCols[x][val] = true; | |
// check the validity of the current square | |
if (uniqBlocks[blockX][val] === true) { | |
console.log(val + " is invalid for the block at (" + x + "," + y + ")"); | |
return false; | |
} | |
uniqBlocks[blockX][val] = true; | |
} | |
// reset | |
uniqRow = {}; | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here are some sample inputs for the function