Created
March 14, 2018 11:31
-
-
Save vamp/54adede2d5c39eb629db6aba64a5cd53 to your computer and use it in GitHub Desktop.
sudoku validator
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
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