[HAI] isValidSudoku WIP

main
Vasily Guzov 1 year ago
parent 9e79211174
commit 0a9d8b23a2

@ -4,7 +4,7 @@ import { isValidSudoku } from "./isValidSudoku.ts";
describe("isValidSudoku", () => { describe("isValidSudoku", () => {
it("true case", () => { it("true case", () => {
const board = let board =
[["5", "3", ".", ".", "7", ".", ".", ".", "."] [["5", "3", ".", ".", "7", ".", ".", ".", "."]
, ["6", ".", ".", "1", "9", "5", ".", ".", "."] , ["6", ".", ".", "1", "9", "5", ".", ".", "."]
, [".", "9", "8", ".", ".", ".", ".", "6", "."] , [".", "9", "8", ".", ".", ".", ".", "6", "."]
@ -19,7 +19,7 @@ describe("isValidSudoku", () => {
}); });
it("false case", () => { it("false case", () => {
const board = let board =
[["8", "3", ".", ".", "7", ".", ".", ".", "."] [["8", "3", ".", ".", "7", ".", ".", ".", "."]
, ["6", ".", ".", "1", "9", "5", ".", ".", "."] , ["6", ".", ".", "1", "9", "5", ".", ".", "."]
, [".", "9", "8", ".", ".", ".", ".", "6", "."] , [".", "9", "8", ".", ".", ".", ".", "6", "."]

@ -3,63 +3,15 @@ export function isValidSudoku(board: string[][]): boolean {
const colTable: Record<string, string[]> = {} const colTable: Record<string, string[]> = {}
const cellTable: Record<string, string[]> = {} const cellTable: Record<string, string[]> = {}
let cellNum = 0;
for (let i = 0; i < board.length; i++) { for (let i = 0; i < board.length; i++) {
if (i + 1 % 3 === 0) cellNum = i; rowTable[i] = board[i].filter(item => item !== ".");
if (new Set(rowTable[i]).size !== rowTable[i].length) return false;
for (let j = 0; j < board[i].length; j++) { colTable[i] = board.map(item => item[i]).filter(item => item !== ".");
// check repeat in rows if (new Set(colTable[i]).size !== rowTable[i].length) return false;
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)
}
} }
// 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 }) console.log({ cellTable, rowTable, colTable })
return true return true
}; };

Loading…
Cancel
Save