Skip to content

Commit 0a064da

Browse files
committed
Add doctest a Sudoku.js
1 parent 194b11b commit 0a064da

File tree

1 file changed

+12
-13
lines changed

1 file changed

+12
-13
lines changed

Backtracking/Sudoku.js

+12-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,17 @@ 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+
this.solve()
5155
// backtracking if the board cannot be solved using current configuration
5256
this.board[y][x] = 0
5357
}
@@ -61,7 +65,6 @@ class Sudoku {
6165
}
6266

6367
printBoard () {
64-
// helper function to display board
6568
for (let i = 0; i < 9; i++) {
6669
if (i % 3 === 0 && i !== 0) console.log('- - - - - - - - - - - -')
6770
console.log(
@@ -73,7 +76,6 @@ class Sudoku {
7376
}
7477

7578
function main () {
76-
// main function with an example
7779
const sudokuBoard = new Sudoku([
7880
[3, 0, 6, 5, 0, 8, 4, 0, 0],
7981
[5, 2, 0, 0, 0, 0, 0, 0, 0],
@@ -85,13 +87,10 @@ function main () {
8587
[0, 0, 0, 0, 0, 0, 0, 7, 4],
8688
[0, 0, 5, 2, 0, 6, 3, 0, 0]
8789
])
88-
89-
sudokuBoard.printBoard()
90-
91-
console.log('\n')
9290
sudokuBoard.solve()
9391

94-
sudokuBoard.printBoard()
92+
// > sudokuBoard.solutionFound
93+
// true
9594
}
9695

9796
main()

0 commit comments

Comments
 (0)