-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
77 lines (74 loc) · 3.09 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<!DOCTYPE html>
<html>
<head>
<title>Sudoku Solver</title>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Sudoku Solver</h1>
<div id="inputsArea"></div>
<div id="resultArea"></div>
<button id="btnGen">Generate</button> <button id="btnSolve">Solve</button>
<script src="sudoku.js"></script>
<script>
(function () {
const inputsArea = document.getElementById("inputsArea");
const resultArea = document.getElementById("resultArea");
const validInputs = new Set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
for (let i = 0; i < 9; i++) {
for (let j = 0; j < 9; j++) {
let newInput = document.createElement("input");
inputsArea.appendChild(newInput);
newInput.className = "sudokuInput";
newInput.id = `input${i}${j}`;
newInput.maxLength = 1;
}
inputsArea.innerHTML += "<br>";
}
document.getElementById("btnSolve").addEventListener("click", () => {
const board = new Array(9).fill(null).map(r => r = new Array(9).fill(0));
for (let i = 0; i < 9; i++) {
for (let j = 0; j < 9; j++) {
const input = document.getElementById(`input${i}${j}`).value;
if (input === "" || input === " ") {
continue;
}
const value = parseInt(input);
if (validInputs.has(value)) {
board[i][j] = value;
} else {
resultArea.innerHTML = "Invalid input";
return;
}
}
}
const solver = new SudokuSolver(board);
if (!solver.isValidBoard()) {
resultArea.innerHTML = "Invalid input";
return;
}
const startTime = new Date().getTime();
if (solver.solve()) {
const elapsedTime = new Date().getTime() - startTime;
resultArea.innerHTML = `Solved in ${elapsedTime}ms`;
for (let i = 0; i < board.length; i++) {
for (let j = 0; j < board[i].length; j++) {
document.getElementById(`input${i}${j}`).value = board[i][j];
}
}
}
});
document.getElementById("btnGen").addEventListener("click", () => {
const generator = new SudokuGenerator();
const board = generator.generate();
for (let i = 0; i < board.length; i++) {
for (let j = 0; j < board[i].length; j++) {
document.getElementById(`input${i}${j}`).value = board[i][j] === 0 ? "" : board[i][j];
}
}
});
})();
</script>
</body>
</html>