Last active
December 14, 2025 14:47
-
-
Save diogohmcruz/944f9173bc9f3f0412efd8c60e75df84 to your computer and use it in GitHub Desktop.
Sudoku Solver
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Sudoku solver using Constraint Logic Programming over Finite Domains (CLP(FD)). | |
| * | |
| * This program defines a `sudoku/1` predicate that solves a Sudoku puzzle. | |
| * The input is a list of lists representing the Sudoku rows, where `_` represents empty cells. | |
| * The program uses constraints to ensure that each number from 1 to 9 appears exactly once in each of the classic | |
| * sudoku constraints: row, column, and 3x3 block. | |
| * | |
| * Requirements: | |
| * - SWI-Prolog with the CLP(FD) library installed. | |
| * | |
| * Instructions: | |
| * 1. Run `consult('sudokuSolver.pl').`; | |
| * 2. Define the puzzle: `Puzzle = [[row1], [row2], ..., [row9]];` | |
| * 3. Call `sudoku(Puzzle).`; | |
| * 4. Call `maplist(writeln, Puzzle).` to display the solution. | |
| * | |
| * Example usage: | |
| * ?- consult('sudokuSolver.pl'). | |
| * ?- Puzzle = [ | |
| * [5,3,_,_,7,_,_,_,_], | |
| * [6,_,_,1,9,5,_,_,_], | |
| * [_,9,8,_,_,_,_,6,_], | |
| * [8,_,_,_,6,_,_,_,3], | |
| * [4,_,_,8,_,3,_,_,1], | |
| * [7,_,_,_,2,_,_,_,6], | |
| * [_,6,_,_,_,_,2,8,_], | |
| * [_,_,_,4,1,9,_,_,5], | |
| * [_,_,_,_,8,_,_,7,9] | |
| * ], | |
| * sudoku(Puzzle), | |
| * maplist(writeln, Puzzle). | |
| */ | |
| :- use_module(library(clpfd)). | |
| sudoku(Rows) :- | |
| length(Rows, 9), | |
| maplist(same_length(Rows), Rows), | |
| append(Rows, Vars), | |
| Vars ins 1..9, | |
| maplist(all_distinct, Rows), | |
| transpose(Rows, Columns), | |
| maplist(all_distinct, Columns), | |
| Rows = [A,B,C,D,E,F,G,H,I], | |
| blocks(A, B, C), | |
| blocks(D, E, F), | |
| blocks(G, H, I), | |
| labeling([ffc], Vars). | |
| blocks([], [], []). | |
| blocks([A,B,C|R1], | |
| [D,E,F|R2], | |
| [G,H,I|R3]) :- | |
| all_distinct([A,B,C,D,E,F,G,H,I]), | |
| blocks(R1, R2, R3). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment