Created
January 18, 2018 01:03
-
-
Save RogWilco/7985a2560e9a066fecfd9b43481a4427 to your computer and use it in GitHub Desktop.
This file contains 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
const board = [ [7, 2, 6, 4, 9, 3, 8, 1, 5], [3, 1, 5, 7, 2, 8, 9, 4, 6], [4, 8, 9, 6, 5, 1, 2, 3, 7], [8, 5, 2, 1, 4, 7, 6, 9, 3], [6, 7, 3, 9, 8, 5, 1, 2, 4], [9, 4, 1, 3, 6, 2, 7, 5, 8], [1, 9, 4, 8, 3, 6, 5, 7, 2], [5, 6, 7, 2, 1, 4, 3, 8, 9], [2, 3, 8, 5, 7, 9, 4, 6, 1], ] | |
/** | |
* Checks if the list of values is a valud sudoku combination of numbers. | |
* | |
* Constraints: | |
* - 9 values total | |
* - Must be integers 1 - 9 | |
* - No duplicate values | |
* | |
* @param {[type]} values [description] | |
* @return {Boolean} [description] | |
*/ | |
var isValid = function(values) { | |
var seen = []; | |
// Not 9 values. | |
if(values.length != 9) { | |
return false; | |
} | |
// Check for duplicates | |
for(var i = 0; i < values.length; i++) { | |
if(seen.indexOf(values[i]) !== -1) { | |
return false; | |
} | |
seen.push(values[i]); | |
} | |
// Only values 1-9 | |
return (seen.length === 9); | |
} | |
/** | |
* Inspects the board to verify all rows, columns, and 3x3 tiles are valid. | |
* | |
* @param {[type]} rows [description] | |
* @return {[type]} [description] | |
*/ | |
var checkBoard = function(board) { | |
var cols = [[], [], [], [], [], [], [], [], []]; | |
var tiles = [[], [], [], [], [], [], [], [], []]; | |
// Check rows | |
for(var i = 0; i < board.length; i++) { | |
if(!isValid(board[i])) { | |
return false; | |
} | |
for(var j = 0; j < board[i].length; j++) { | |
// Build column list | |
cols[j].push(board[i][j]); | |
// Build tile list | |
if(i <= 3) { | |
if(j <= 3) { | |
tiles[0].push(board[i][j]); | |
} | |
else if(j <= 6) { | |
tiles[1].push(board[i][j]); | |
} | |
else if(j <= 9) { | |
tiles[2].push(board[i][j]); | |
} | |
} | |
else if(i <= 6) { | |
if(j <= 3) { | |
tiles[3].push(board[i][j]); | |
} | |
else if(j <= 6) { | |
tiles[4].push(board[i][j]); | |
} | |
else if(j <= 9) { | |
tiles[5].push(board[i][j]); | |
} | |
} | |
else if(i <= 9) { | |
if(j <= 3) { | |
tiles[6].push(board[i][j]); | |
} | |
else if(j <= 6) { | |
tiles[7].push(board[i][j]); | |
} | |
else if(j <= 9) { | |
tiles[8].push(board[i][j]); | |
} | |
} | |
} | |
} | |
// Check columns | |
for(var i = 0; i < cols.length; i++) { | |
if(!isValid(cols[i])) { | |
return false; | |
} | |
} | |
console.log(tiles); | |
// Check tiles | |
for(var i = 0; i < tiles.length; i++) { | |
if(!isValid(tiles[i])) { | |
return false; | |
} | |
} | |
return true; | |
} | |
if(checkBoard(board)) { | |
console.log('Board is VALID!'); | |
} | |
else { | |
console.log('Board is INVALID!'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment