Skip to content

Instantly share code, notes, and snippets.

@nakaz
Last active May 28, 2016 20:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nakaz/0d5390057d99256878ab to your computer and use it in GitHub Desktop.
Save nakaz/0d5390057d99256878ab to your computer and use it in GitHub Desktop.
Answer key for SudokuValidator Challenge
/* SudokuValidator(sudoku)
*
* @param sudoku a multidimensional array containing the sudoku puzzle
*
* @public property sudoku the sudoku grid
*
* @public method validate(num) num is the squared value or max value of sudoku number
for example: 9(result of 3x3 grid) or 4 (2x2).
*/
exports.SudokuValidator = SudokuValidator;
function SudokuValidator(sudoku){
this.sudoku = sudoku;
}
SudokuValidator.prototype.validate = function(num){
let sudoku = this.sudoku;
let rows, cols, grid;
organize(sudoku);
function check (data){
for (var row = 0; row < num; row++){
data[row].sort();
for(var col = 0; col < num; col++){
let val = data[row][col]
let nextVal = data[row][col + 1];
if (!(val && val > 0 && val < num+1)){
return false;
}
if (col !== num-1 && val === nextVal){
return false;
}
}
}
return true;
}
function organize (data){
rows = data;
cols = [];
grid = [];
for (var i = 0; i < num; i++){
cols.push([]);
grid.push([]);
}
for (var row = 0; row < num; row++){
for (var col = 0; col < num; col++){
cols[col][row] = data[row][col];
gridRow = Math.floor(row / Math.sqrt(num));
gridCol = Math.floor(col / Math.sqrt(num));
gridIndex = gridRow * Math.sqrt(num) + gridCol;
grid[gridIndex].push(data[row][col]);
}
}
}
return (check(rows) && check(cols) && check(grid));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment