Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@vamp
Created March 14, 2018 11:31
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 vamp/54adede2d5c39eb629db6aba64a5cd53 to your computer and use it in GitHub Desktop.
Save vamp/54adede2d5c39eb629db6aba64a5cd53 to your computer and use it in GitHub Desktop.
sudoku validator
function validate(board) {
const input = getArray(board);
const predicates = [
hasValidStructure,
createDataValidator([9, 1]),
createDataValidator([1, 9]),
createDataValidator([3, 3])
];
const isValid = predicates.every(fn => fn(input));
return isValid;
}
function hasValidStructure(data) {
if (!Array.isArray(data)) {
return false;
}
for (let row of data) {
if (!Array.isArray(row) || !row.every(isValid)) {
return false;
}
}
return true;
}
function createDataValidator(size = [3, 3]) {
return (data) => {
for (let index of range(0, 9)) {
if (!isUnique(slice(data, index, size))) {
return false;
}
}
return true;
}
}
function* range(from, to) {
while (from < to) {
yield from++;
}
}
function* pick(data, row, col) {
for (let i of row()) {
for (let j of col()) {
yield data[i][j];
}
}
}
function* slice(data, index, size = [3, 3], width = 9) {
const s = (index * size[0]);
const row = ((s / width) | 0) * size[1];
const col = (s % width);
yield* pick(data, () => range(row, row + size[1]), () => range(col, col + size[0]));
}
function isUnique(data) {
let array = Array.from(data).filter(entry => entry !== null).map(entry => +entry);
return (new Set(array).size === array.length);
}
function isValid(entry) {
return (entry === null) || (+entry === (entry|0)) && (entry > 0 && entry < 10);
}
function getArray(data) {
try {
return (Array.isArray(data)) ? data : JSON.parse(data);
} catch (e) {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment