Skip to content

Commit 8d2b627

Browse files
committed
Add doctest a Sudoku.js
1 parent 194b11b commit 8d2b627

File tree

1 file changed

+14
-13
lines changed

1 file changed

+14
-13
lines changed

Backtracking/Sudoku.js

+14-13
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,17 @@
11
class Sudoku {
2-
// Sudoku Class to hold the board and related functions
32
constructor (board) {
43
this.board = board
4+
this.solutionFound = false
55
}
66

77
findEmptyCell () {
8-
// Find a empty cell in the board (returns [-1, -1] if all cells are filled)
98
for (let i = 0; i < 9; i++) {
109
for (let j = 0; j < 9; j++) {
1110
if (this.board[i][j] === 0) return [i, j]
1211
}
1312
}
14-
return [-1, -1]
13+
const noEmptyCell = [-1, -1]
14+
return noEmptyCell
1515
}
1616

1717
check ([y, x], value) {
@@ -41,13 +41,19 @@ class Sudoku {
4141
solve () {
4242
const [y, x] = this.findEmptyCell()
4343

44-
// checking if the board is complete
45-
if (y === -1 && x === -1) return true
44+
const boardIsComplete = y === -1 && x === -1
45+
if (boardIsComplete) {
46+
this.printBoard()
47+
this.solutionFound = true
48+
return true
49+
}
4650

4751
for (let val = 1; val < 10; val++) {
4852
if (this.check([y, x], val)) {
4953
this.board[y][x] = val
50-
if (this.solve()) return true
54+
if (this.solve()) {
55+
return true
56+
}
5157
// backtracking if the board cannot be solved using current configuration
5258
this.board[y][x] = 0
5359
}
@@ -61,7 +67,6 @@ class Sudoku {
6167
}
6268

6369
printBoard () {
64-
// helper function to display board
6570
for (let i = 0; i < 9; i++) {
6671
if (i % 3 === 0 && i !== 0) console.log('- - - - - - - - - - - -')
6772
console.log(
@@ -73,7 +78,6 @@ class Sudoku {
7378
}
7479

7580
function main () {
76-
// main function with an example
7781
const sudokuBoard = new Sudoku([
7882
[3, 0, 6, 5, 0, 8, 4, 0, 0],
7983
[5, 2, 0, 0, 0, 0, 0, 0, 0],
@@ -85,13 +89,10 @@ function main () {
8589
[0, 0, 0, 0, 0, 0, 0, 7, 4],
8690
[0, 0, 5, 2, 0, 6, 3, 0, 0]
8791
])
88-
89-
sudokuBoard.printBoard()
90-
91-
console.log('\n')
9292
sudokuBoard.solve()
9393

94-
sudokuBoard.printBoard()
94+
// > sudokuBoard.solutionFound
95+
// true
9596
}
9697

9798
main()

0 commit comments

Comments
 (0)