Sudoku Solver

Tutorial kali ini kita akan membuat game sudoku solver mulai dari membuat psudo-code, implementasi pseudo-code ke dalam bahasa pemrograman, kemudian membuat tampilan.
Hasilnya nanti kurang lebih seperti ini yaa demo

Pseudo Code

Ukuran board sudoku 9 x 9
Langkah pertama membuat method checkBoard() terlebih dahulu, yaitu
1. cek secara vertikal & horizontal
2. cek secara grid

CEK BOARD  METHOD checkBoard()
FOR i = 0 UNTIL i = 8 AND i++
FOR j = 0 UNTIL j = 8 AND j++
IF borads[i][j]
SET isPerp = checkPerp(i, j, boards[i][j]) // CEK PERPENDICULAR
SET isGrid = checkGrid(i, j, boards[i][j]) // CEK GRID
IF !isPerp || !isGrid
RETURN FALSE
END IF
END IF
END FOR
END FOR
RETURN TRUE


CEK PERPENDICULAR METHOD checkPerp(i, j, fill)
FOR n = 0 UNTIL n = 8 AND n++
// Cek Horizontal
IF board[i][n] === fill && j !== n
RETURN FALSE
END IF

// Cek Vertikal
IF board[n][j] === fill && i !== n
RETURN FALSE
END IF
END FOR


CEK GRID METHOD checkGrid(i, j, fill)
// NORMALISASI i
IF i == 0 || i == 1 || i == 2
SET i = 0
EN IF

IF i == 3 || i == 4 || i == 5
SET i = 3
EN IF

IF i == 6 || i == 7 || i == 8
SET i = 6
EN IF

// NORMALISASI j
IF j == 0 || j == 1 || j == 2
SET j = 0
EN IF

IF j == 3 || j == 4 || j == 5
SET j = 3
EN IF

IF j == 6 || j == 7 || j == 8
SET j = 6
EN IF

// CEK GRID
FOR n = i UNTIL n <= i + 2 AND n++
FOR m = j UNTIL j <= j + 2 AND m++
IF n != i && m != j && board[n][m] !== fill
RETURN FALSE
END IF
END FOR
END FOR
RETURN TRUE

Langkah ke-2 yaitu membuat method solve() dengan mengimplementasikan backtrack
*backtrack adalah sebuah cara untuk menyimpan setiap langkah / proses atau dengan kata lain undo

// backtrack denga  format
// [
// {
// i: 0,
// j: 0,
// val: 5
// }
// ]
SET isInvalidBoard = false
SET histories = []
checkBoard()

FOR i = 0 UNTIL i = 8
FOR j = 0 UNTIL j = 8

IF board[i][j] === null
| // ISI VALUE ANTARA 1 - 9
| FOR val = 1 UNTIL val = 9 AND val++
| SET isPerp = checkPerp(i, j,val) // CEK PERPENDICULAR
| SET isGrid = checkGrid(i, j,val) // CEK GRID
|
| IF isPerp && isGrid
| | SET board[i][j] = val
| | PUSH {i, j, val} TO histories
| ELSE IF val === 9
| | // DILAKUKAN BACKTRACK (cari yang valuenya < 9)
| | SET FLAG = TRUE
| | WHILE FLAG
| | SET back = POP histories
| | IF back
| | | IF back.val < 9
| | | | SET FLAG = FALSE
| | | | SET i = back.i
| | | | SET j = back.j
| | | | SET board[i][j] = board.val + 1
| | | ELSE
| | | | SET board[back.i][back.j] = NULL
| | | END IF
| | ELSE
| | | SET FLAG = FALSE
| | | SET isInvalidBoard = TRUE
| | | BREAK ALL LOOPING
| | END IF
| | END WHILE
| |
| END IF
| IF !BACKTRACK j++
| END FOR
END IF
IF !BACKTRACK i++
END FOR
END FOR