[HAI] isValidSudoku WIP
This commit is contained in:
@@ -3,63 +3,15 @@ export function isValidSudoku(board: string[][]): boolean {
|
||||
const colTable: Record<string, string[]> = {}
|
||||
const cellTable: Record<string, string[]> = {}
|
||||
|
||||
let cellNum = 0;
|
||||
|
||||
for (let i = 0; i < board.length; i++) {
|
||||
if (i + 1 % 3 === 0) cellNum = i;
|
||||
|
||||
for (let j = 0; j < board[i].length; j++) {
|
||||
// check repeat in rows
|
||||
const rowValue = board[i][j];
|
||||
const rowKey = i + "_" + cellNum;
|
||||
if (rowValue === ".") continue;
|
||||
|
||||
if (
|
||||
!rowTable[rowKey]
|
||||
) {
|
||||
rowTable[rowKey] = [rowValue];
|
||||
} else {
|
||||
if (rowTable[rowKey].includes(rowValue)) return false;
|
||||
rowTable[i + "_" + cellNum].push(rowValue);
|
||||
}
|
||||
}
|
||||
|
||||
// check repeat in collumns
|
||||
const collValue = board[i][i];
|
||||
const collKey = i + "_" + cellNum;
|
||||
|
||||
if (collValue === ".") continue;
|
||||
|
||||
if (!colTable[collKey]) {
|
||||
colTable[collKey] = [collValue];
|
||||
} else {
|
||||
if (colTable[collKey] && colTable[collKey].includes(collValue)) return false;
|
||||
colTable[collKey].push(collValue)
|
||||
}
|
||||
rowTable[i] = board[i].filter(item => item !== ".");
|
||||
if (new Set(rowTable[i]).size !== rowTable[i].length) return false;
|
||||
colTable[i] = board.map(item => item[i]).filter(item => item !== ".");
|
||||
if (new Set(colTable[i]).size !== rowTable[i].length) return false;
|
||||
}
|
||||
|
||||
// create cellTable
|
||||
for (let cellKey = 0; cellKey < board.length; cellKey++) {
|
||||
if (cellKey + 1 % 3 === 0) cellNum = (cellKey + 1) / 3;
|
||||
let rowKey = cellKey + "_" + cellNum;
|
||||
let rowValues = rowTable[rowKey];
|
||||
|
||||
if (!cellTable[cellKey]) {
|
||||
cellTable[cellKey] = rowValues;
|
||||
} else {
|
||||
rowValues.forEach(value => {
|
||||
if (
|
||||
cellTable[cellKey].includes(value)
|
||||
) {
|
||||
return false
|
||||
}
|
||||
})
|
||||
cellTable[cellKey].concat(rowValues);
|
||||
}
|
||||
}
|
||||
|
||||
console.log({ cellTable, rowTable, colTable })
|
||||
|
||||
|
||||
return true
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user