-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunction.js
More file actions
256 lines (243 loc) · 8.73 KB
/
function.js
File metadata and controls
256 lines (243 loc) · 8.73 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
let hintCount = 0;
let diffNum = 30;
let board = Array.from({ length: 9 }, () => Array(9).fill(0));
const difficultyBtn = document.querySelectorAll('.diffBtn');
difficultyBtn.forEach(button => {
button.addEventListener('click', () => {
difficultyBtn.forEach(btn => {
btn.classList.remove('active');
});
button.classList.add('active');
const selectDiff = button.dataset.difficulty;
if (selectDiff === 'easy') {
diffNum = 30;
}
else if (selectDiff == 'medium') {
diffNum = 40;
}
else {
diffNum = 50;
}
});
});
createBoard();
function createBoard() {
let sudoBo = document.querySelector(".sudokuBoard");
sudoBo.innerHTML = "";
for (let i = 0; i < 9; i++) {
for (let j = 0; j < 9; j++) {
let ele = document.createElement("input");
ele.maxlength = 1;
ele.type = "text";
ele.dataset.row = i;
ele.dataset.col = j;
sudoBo.appendChild(ele);
}
}
hintCount = 0;
if(document.getElementById('hint-count')) {
document.getElementById('hint-count').textContent = hintCount;
}
}
function fillBoard(tempBo) {
document.querySelectorAll(".sudokuBoard input").forEach(cell => {
let row = parseInt(cell.dataset.row);
let col = parseInt(cell.dataset.col);
cell.value = tempBo[row][col] == 0 ? "" : tempBo[row][col];
});
}
function generate() {
board = Array.from({length: 9},() => Array(9).fill(0)); //resetting board each time
solveSudoku(board, true);
let puzzleGenerated = JSON.parse(JSON.stringify(board));
let cellToRemove = diffNum;
while(cellToRemove > 0){
let row = Math.floor(Math.random() * 9);
let col = Math.floor(Math.random() * 9);
if(puzzleGenerated[row][col] != 0){
puzzleGenerated[row][col] = 0;
cellToRemove--;
}
}
fillBoard(puzzleGenerated);
hintCount = 0;
document.getElementById('hint-count').textContent = hintCount;
}
function giveHint() {
//give a hint of eligible numbers for current box or complete the current box with valid input
let currentBoard = readBoard();
let solutionBoard = JSON.parse(JSON.stringify(currentBoard));
if (!solveSudoku(solutionBoard)) {
alert("This puzzle has no solution!");
return;
}
for (let r = 0; r < 9; r++) {
for (let c = 0; c < 9; c++) {
if (currentBoard[r][c] == 0) {
let correctValue = solutionBoard[r][c];
let cell = document.querySelector(`.sudokuBoard input[data-row="${r}"][data-col="${c}"]`);
cell.value = correctValue;
cell.style.backgroundColor = '#ffc107';
cell.style.color = '#212529';
setTimeout(() => {
cell.style.backgroundColor = 'black';
cell.style.color = 'white';
}, 1000);
hintCount++;
document.getElementById('hint-count').textContent = hintCount;
return;
}
}
}
alert("The board is already complete!");
}
function readBoard() {
let tempBoard = Array.from({ length: 9 }, () => Array(9).fill(0));
document.querySelectorAll(".sudokuBoard input").forEach(cell => {
let row = parseInt(cell.dataset.row);
let col = parseInt(cell.dataset.col);
let val = cell.value == "" ? 0 : parseInt(cell.value);
tempBoard[row][col] = isNaN(val) ? 0 : val;
});
return tempBoard;
}
function solve() {
let currBoard = readBoard();
if (!isBoardValid(currBoard)) {
return;
}
if (solveSudoku(currBoard)) {
fillBoard(currBoard);
} else {
alert("No solution exist");
}
}
function isBoardValid(board) {
for (let i = 0; i < 9; i++) {
for (let j = 0; j < 9; j++) {
let val = board[i][j];
if (val != 0) {
board[i][j] = 0;
if (!isValid(board, i, j, val)) {
board[i][j] = val;
alert(`Invalid Board!, Duplicates entries found at Row-${i + 1} and Column-${j + 1}`);
return false;
}
}
board[i][j] = val;
}
}
return true;
}
// function solveSudoku(board) {
// //find empty cell
// for (let i = 0; i < board.length; i++) {
// for (let j = 0; j < board[0].length; j++) {
// if (board[i][j]==0) {
// for (let c = 1; c <= 9; c++) {
// if (isValid(board, i, j, c)) {
// board[i][j] = c; //if valid , enter current c in current cell and check for next empty cell by recusrsion, and if at some next empty cell no valid input is possible , then return false and backtrack and try next digit c.
// if (solveSudoku(board)) { return true; } //if all empty cell return true, then the current input is valid
// else { board[i][j] = 0; } //if not, then make the current input empty again and try next c
// }
// }
// return false; //return false if no input number is valid for current cell
// }
// }
// }
// return true; //if no empty cell left and false not returned till now, that means sudoko is solved
// }
function solveSudoku(board, randomize = false) {
//fiding best empty cell that have least possibles moves which will results into less efforts
let bestCell = findBestEmptyCell(board)
if (bestCell == null) {
return true;
}
if (bestCell.candidates === 0) {
return false;
}
let {row,col} = bestCell;
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
if (randomize) {
numbers.sort(() => Math.random() - 0.5);
}
for (let c of numbers) {
if (isValid(board,row,col,c)) {
board[row][col] = c;
if (solveSudoku(board,randomize)) {
return true;
}
board[row][col] = 0;
}
}
return false;
}
function isValid(board, row, col, c) {
for (let i = 0; i < 9; i++) {
if (board[row][i] == c) { return false; }
if (board[i][col] == c) { return false; }
if (board[3 * Math.floor(row / 3) + Math.floor(i / 3)][3 * Math.floor(col / 3) + Math.floor(i % 3)] == c) { return false; }
}
return true;
}
function findBestEmptyCell(board) {
let bestCell = null;
let minCandidates = 10;
for (let r = 0; r < 9; r++) {
for (let c = 0; c < 9; c++) {
if (board[r][c] == 0) {
let numCandidates = 0;
for (let n = 1; n <= 9; n++) {
if (isValid(board, r, c, n)) {
numCandidates++;
}
}
if (numCandidates == 0) {
return { row: r, col: c, candidates: 0 };
}
if (numCandidates < minCandidates) {
minCandidates = numCandidates;
bestCell = { row: r, col: c };
}
}
}
}
return bestCell;
}
document.addEventListener('DOMContentLoaded', (event) => {
const navNewBtn = document.querySelector('.navNew');
const navCustomBtn = document.querySelector('.navCustom');
const navSolveBtn = document.querySelector('.navSolve');
const navClearBtn = document.querySelector('.navClear');
const navHintBtn = document.querySelector('.navHint');
const navSaveBtn = document.querySelector('.navSave');
const navLoadBtn = document.querySelector('.navLoad');
if(navNewBtn) navNewBtn.addEventListener('click', generate);
if(navCustomBtn) navCustomBtn.addEventListener('click', createBoard);
if(navSolveBtn) navSolveBtn.addEventListener('click', solve);
if(navClearBtn) navClearBtn.addEventListener('click', createBoard);
if(navHintBtn) navHintBtn.addEventListener('click', giveHint);
if(navSaveBtn) navSaveBtn.addEventListener('click', saveGame);
if(navLoadBtn) navLoadBtn.addEventListener('click', loadGame);
});
function saveGame() {
let currentBoard = readBoard();
const gameState = {
board: currentBoard,
hints: hintCount,
};
localStorage.setItem('sudokuSaveState', JSON.stringify(gameState));
alert("Game Saved!");
}
function loadGame() {
const savedStateJSON = localStorage.getItem('sudokuSaveState');
if (savedStateJSON) {
const gameState = JSON.parse(savedStateJSON);
fillBoard(gameState.board);
hintCount = gameState.hints || 0;
document.getElementById('hint-count').textContent = hintCount;
alert("Game Loaded!");
} else {
alert("No saved game found.");
}
}