Created
February 27, 2019 13:59
-
-
Save yosevu/7de01b5d1d63ad1d5269660082997057 to your computer and use it in GitHub Desktop.
sudoku-validator
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
| function getIndex(i) { | |
| return Math.floor(i / 3); | |
| } | |
| function fillArray(len, item) { | |
| return new Array(len).fill(item); | |
| } | |
| function isValid(totals) { | |
| const result = Object.values(totals).every(total => { | |
| return total.flat().every(value => value === 45); | |
| }); | |
| return result; | |
| } | |
| function sudokuReducer(sums, row, i) { | |
| return row.reduce((sums, value, j) => { | |
| sums.rows[i] += value; | |
| sums.cols[j] += value; | |
| sums.grids[getIndex(i)][getIndex(j)] += value; | |
| return sums; | |
| }, sums); | |
| } | |
| function validate(board) { | |
| const sums = { | |
| rows: fillArray(9, 0), | |
| cols: fillArray(9, 0), | |
| grids: [[0, 0, 0], [0, 0, 0], [0, 0, 0]], | |
| // grids: fillArray(3, fillArray(3, 0)), | |
| }; | |
| const reducedBoard = board.reduce(sudokuReducer, sums); | |
| return isValid(reducedBoard); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment