Created
February 1, 2019 15:29
-
-
Save JFrankfurt/3e1f9f68e49b263db32574091eef6bf3 to your computer and use it in GitHub Desktop.
sudoku validation
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 rowValidity(row: number[]): boolean { | |
const numSet = new Set(row); | |
const deDupedRow = Array.from(numSet); | |
const allNumsInValidRange = deDupedRow.reduce((acc, cur) => { | |
if (cur < 1 || cur > 9 || acc === false) { | |
return false; | |
} else { | |
return true; | |
} | |
}, true); | |
const inputLengthIsValid = row.length === 9; | |
const noDuplicates = deDupedRow.length === 9; | |
return allNumsInValidRange && inputLengthIsValid && noDuplicates; | |
} | |
function validityTest(puzzle: number[][]): boolean { | |
const allRowsAreValid = puzzle.reduce((acc, row) => acc ? rowValidity(row) : false, true); | |
console.log('allRowsAreValid:', allRowsAreValid); | |
let allColumnsValid = true; | |
for (let i = 0; i < puzzle.length; i++) { | |
if (allColumnsValid) { | |
let column = puzzle.map(row => row[i]) | |
allColumnsValid = rowValidity(column) | |
} | |
} | |
console.log('allColumnsValid:', allColumnsValid); | |
let allSquaresValid = true; | |
for (let i = 0; i < puzzle.length; i += 3) { | |
for (let j = 0; j < puzzle.length; j += 3) { | |
if (allSquaresValid) { | |
const square = [ | |
puzzle[i][j], puzzle[i+1][j], puzzle[i+2][j], | |
puzzle[i][j+1], puzzle[i+1][j+1], puzzle[i+2][j+1], | |
puzzle[i][j+2], puzzle[i+1][j+2], puzzle[i+2][j+2] | |
] | |
allSquaresValid = rowValidity(square) | |
} | |
} | |
} | |
console.log('allSquaresValid:', allSquaresValid); | |
return allRowsAreValid && allColumnsValid && allSquaresValid; | |
} | |
const input1 = [ | |
[5, 3, 4, 6, 7, 8, 9, 1, 2], | |
[6, 7, 2, 1, 9, 5, 3, 4, 8], | |
[1, 9, 8, 3, 4, 2, 5, 6, 7], | |
[8, 5, 9, 7, 6, 1, 4, 2, 3], | |
[4, 2, 6, 8, 5, 3, 7, 9, 1], | |
[7, 1, 3, 9, 2, 4, 8, 5, 6], | |
[9, 6, 1, 5, 3, 7, 2, 8, 4], | |
[2, 8, 7, 4, 1, 9, 6, 3, 5], | |
[3, 4, 5, 2, 8, 6, 1, 7, 9] | |
]; | |
const input2 = [ | |
[5, 3, 4, 6, 7, 8, 9, 1, 2], | |
[6, 7, 2, 1, 9, 5, 3, 4, 1], | |
[1, 9, 8, 3, 4, 2, 5, 6, 7], | |
[8, 5, 9, 7, 6, 1, 4, 2, 3], | |
[4, 2, 6, 8, 5, 3, 7, 9, 1], | |
[7, 1, 3, 9, 2, 4, 8, 5, 6], | |
[9, 6, 1, 5, 3, 7, 2, 8, 4], | |
[2, 8, 7, 4, 1, 9, 6, 3, 5], | |
[3, 4, 5, 2, 8, 6, 1, 7, 9] | |
]; | |
console.log(validityTest(input1)) | |
console.log(validityTest(input2)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment