Created
February 8, 2017 06:31
-
-
Save hammeiam/e3b6d887c27d1bfc59a12a1dc61f3099 to your computer and use it in GitHub Desktop.
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
class SudokuValidator { | |
constructor(board) { | |
if (board.length !== board[0].length) { | |
throw new Error('Board must be square'); | |
} | |
if (Math.sqrt(board.length) !== Math.floor(Math.sqrt(board.length))) { | |
throw new Error('Board size must be a square number') | |
} | |
this.board = board; | |
this.size = board.length; | |
this.gridSize = Math.sqrt(board.length); | |
this.axes = ['row', 'col']; | |
} | |
_buildTracker = () => new Array(this.size) | |
_validateAxis = (axis) => { | |
if (!this.axes.find(i => i === axis)) throw new Error('Axis must be either col or row'); | |
let tracker; | |
for (let row = 0; row < this.size; row++) { | |
for (let col = 0; col < this.size; col++) { | |
tracker = this._buildTracker(); | |
const cell = this.board[axis === 'row' ? col : row][axis === 'row' ? row : col]; | |
if (tracker[cell]) return false; | |
tracker[cell] = true; | |
} | |
} | |
return true; | |
} | |
_validateSquares = () => { | |
let tracker; | |
for (let bigRow = 0; bigRow < this.size; bigRow += this.gridSize) { | |
for (let bigCol = 0; bigCol < this.size; bigCol += this.gridSize) { | |
tracker = this._buildTracker(); | |
for (let littleRow = 0; littleRow < this.gridSize; littleRow++) { | |
for (let littleCol = 0; littleCol < this.gridSize; littleCol++) { | |
const cell = this.board[bigRow + littleRow][bigCol + littleCol]; | |
if (tracker[cell]) return false; | |
tracker[cell] = true; | |
} | |
} | |
} | |
} | |
return true; | |
} | |
validate = () => { | |
return this._validateAxis('row') && | |
this._validateAxis('col') && | |
this._validateSquares(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this implementation assumes cell values are 0-9