in Artificial Intelligence, Prolog, Puzzle solving

Sudoku solver

It’s pretty straightforward to make a Sudoku solver in Prolog especially when applying CLP (Constraint Logic Programming).

Here is how to use my program:

:- solve_sudoku.

Then you can enter the known numbers one by one.

+-+-+-+-+-+-+
|9 8| 5 |  7|
|72 |1

When complete, the program determines and prints the solution.

+-+-+-+-+-+-+
|938|254|617|
|726|193|854|
|514|876|329|
+-+-+-+-+-+-+
|692|387|145|
|187|465|293|
|453|921|768|
+-+-+-+-+-+-+
|345|712|986|
|871|649|532|
|269|538|471|
+-+-+-+-+-+-+

Typing

:- sudoku(L), write_sol(L).

Gives

+-+-+-+-+-+-+
|123|456|789|
|456|789|123|
|789|123|456|
+-+-+-+-+-+-+
|214|365|897|
|365|897|214|
|897|214|365|
+-+-+-+-+-+-+
|531|642|978|
|642|978|531|
|978|531|642|
+-+-+-+-+-+-+

By pressing ; over and over again, you could enumerate all 6,670,903,752,021,072,936,960 possible Sudoku solution grids, but this might take a while..

It shouldn’t be too hard to extend this program to actually create new puzzles. If anyone does, let me know.

The prolog environment I used here is SWI-Prolog.

Write a Comment

Comment