-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
101 lines (86 loc) · 2.25 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
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 = () => {
SudokuSolver(board, 0, 0, 9);
};
function isValid(board ,i,j, num,n){
//row and column check
for(let x=0;x<n;x++){
if(board[i][x]==num || board[x][j]==num){
return false;
}
}
//submatrix check
let rn=Math.sqrt(n);
let si=i-i%rn;
let sj=j-j%rn;
for(let x=si;x<si;x++){
for(let y=sj;y<sj+rn;y++){
if(board[x][y]==num){
return false;
}
}
}
return true;
}
function SudokuSolver(board,
i,j,n){
//Base case
if(i==n){
//Print(board,n);
FillBoard(board)
return true;
}
//if we are not inside the board
if(j==n){
return SudokuSolver(board,i+1,0,n);
}
//if cell is already filled -> just move ahead
if(board[i][j]!=0){
return SudokuSolver(board,i,j+1,n);
}
//we try to fill the cell with an appropriate number
for(let num=1;num<=9;num++){
//Check if the number can be filled
if(isValid(board,i,j,num,n)){
board[i][j]=num;
let subAns = SudokuSolver(board,i,j+1,n);
if(subAns){
return true;
}
//Backtracking ->undo the change
board[i][j]=0;
}
}
return false;
}