Last active
August 17, 2018 16:30
-
-
Save mavharsha/ef57b3985733aaa06d3d7f512ee47c1e to your computer and use it in GitHub Desktop.
Check if the 9*9 Matrix grid is valid sudoku solution.
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
const validGrid = [[8,3,5,4,1,6,9,2,7], | |
[2,9,6,8,5,7,4,3,1], | |
[4,1,7,2,9,3,6,5,8], | |
[5,6,9,1,3,4,7,8,2], | |
[1,2,3,6,7,8,5,4,9], | |
[7,4,8,5,2,9,1,6,3], | |
[6,5,2,7,8,1,3,9,4], | |
[9,8,1,3,4,5,2,7,6], | |
[3,7,4,9,6,2,8,1,5]]; | |
const invalidGrid =[[8,3,5,4,1,6,9,2,7], | |
[2,9,6,8,5,7,4,3,1], | |
[4,1,7,2,9,3,6,5,8], | |
[5,6,9,1,3,4,7,8,2], | |
[1,2,3,6,7,8,5,4,9], | |
[7,4,8,5,2,9,1,6,3], | |
[6,5,2,7,8,1,3,9,4], | |
[9,8,1,3,4,5,2,7,6], | |
[3,7,4,9,6,2,8,1,1]]; | |
function flatten(array) { | |
return array.reduce((acc, sub) => (Array.isArray(sub)? acc.concat(flatten(sub)) : acc.concat(sub)), []); | |
} | |
function getArray(grid, rowLowerBound, rowUpperBound, columnLowBound, columnBound) { | |
return grid.filter((row, index) => index >= rowLowerBound && index < rowUpperBound).map((row) => row.filter((item, index) => index >= columnLowBound && index < columnBound)) | |
} | |
function getColumnFromGrid(grid, columnIndex) { | |
return grid.map((row) => row[columnIndex]) | |
} | |
function getRowFromGrid(grid, rowIndex) { | |
return grid[rowIndex] | |
} | |
function validateSudokuRow(row) { | |
const currentRow = row.slice(0).sort(); | |
for(let index = 0; index < currentRow.length; index++) { | |
if(currentRow[index] !== (index + 1)) { | |
console.error('Error in array', Temprow) | |
return false; | |
} | |
} | |
return true; | |
} | |
function validateGrid(grid) { | |
//validate rows and columns | |
for(let index = 0; index < grid.length; index++) { | |
if(!validateSudokuRow(getRowFromGrid(grid, index))) { console.log('Row', index + 1); return false;} | |
if(!validateSudokuRow(getColumnFromGrid(grid, index))) { console.log('Column', index + 1); return false;} | |
} | |
// validate 3*3 squares | |
for(let rowBound = 3; rowBound < 10; rowBound = rowBound + 3){ | |
for(let colBound = 3; colBound < 10; colBound = colBound + 3){ | |
if(!validateSudokuRow(flatten(getArray(grid, rowBound -3, rowBound, colBound - 3, colBound)))) { return false;} | |
} | |
} | |
return true; | |
} | |
console.log(validateGrid(validGrid)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment