-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
104 lines (90 loc) · 2.21 KB
/
script.js
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
var arr = [[], [], [], [], [], [], [], [], []]
for (var i = 0; i < 9; i++) {
for (var j = 0; j < 9; j++) {
arr[i][j] = document.getElementById(i * 9 + j);
}
}
var board = [[], [], [], [], [], [], [], [], []]
function FillBoard(board) {
for (var i = 0; i < 9; i++) {
for (var j = 0; j < 9; j++) {
if (board[i][j] != 0) {
arr[i][j].innerText = board[i][j]
}
else
arr[i][j].innerText = ''
}
}
}
let GetPuzzle = document.getElementById('GetPuzzle')
let SolvePuzzle = document.getElementById('SolvePuzzle')
GetPuzzle.onclick = function () {
var xhrRequest = new XMLHttpRequest()
xhrRequest.onload = function () {
var response = JSON.parse(xhrRequest.response)
console.log(response)
board = response.board
FillBoard(board)
}
xhrRequest.open('get', 'https://sugoku.onrender.com/board?difficulty=easy')
//we can change the difficulty of the puzzle the allowed values of difficulty are easy, medium, hard and random
xhrRequest.send()
}
SolvePuzzle.onclick = () => {
sudukoSolver(board, 0, 0, 9);
};
function isSafe(board,row,col,val,n) {
for (let i = 0; i<n; i++) {
// row check
if (board[row][i] == val || board[i][col]==val)
return false;
// col check
// if (board[i][col] == val)
// return false;
// 3*3matrix check
// if (board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == val)
// return false;
}
//submatrix check
let rn=Math.sqrt(n);
let si= row-row%rn;
let sj= col-col%rn;
for(let x=si; x<si+rn; x++){
for(let y=sj; y<sj+rn; y++){
if(board==val){
return false;
}
}
}
return true;
}
function sudukoSolver(board,row,col,n) {
// base case
if (row == n) {
//print(board, n);
FillBoard(board)
return true;
}
// if we at last col
if (col == n) {
return sudukoSolver(board, row + 1, 0, n);
}
// if cell is already filled
if (board[row][col] != 0) {
return sudukoSolver(board, row, col + 1, n);
}
for (let val = 1; val <= 9; val++) {
// check val is safe or not?
if (isSafe(board, row, col, val, n)) {
board[row][col] = val;
// recursive call
let aagesolpossible = sudukoSolver(board, row, col + 1, n);
if (aagesolpossible) {
return true;
}
// backtracking
board[row][col] = 0;
}
}
return false;
}