Skip to content

Instantly share code, notes, and snippets.

@yosevu
Created February 27, 2019 13:59
Show Gist options
  • Select an option

  • Save yosevu/7de01b5d1d63ad1d5269660082997057 to your computer and use it in GitHub Desktop.

Select an option

Save yosevu/7de01b5d1d63ad1d5269660082997057 to your computer and use it in GitHub Desktop.
sudoku-validator
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