% render solutions nicely. :- use_rendering(sudoku). :- use_module(library(clpfd)). % Example by Markus Triska, taken from the SWI-Prolog manual. sudoku(Rows) :- length(Rows, 9), % 9 rows maplist(same_length(Rows), Rows), % of the same lenght (9) append(Rows, Vs), % flatten to a list of elements Vs ins 1..9, % constrained into the 1..9 integers maplist(all_distinct, Rows), % each row must contain different values transpose(Rows, Columns), % get the transposed matrix maplist(all_distinct, Columns), % each column must contain different values Rows = [A,B,C,D,E,F,G,H,I], % given the rows blocks(A, B, C), % impose constraints on the first three rows blocks(D, E, F), % second 3 blocks(G, H, I). % last 3 blocks([], [], []). % base case for empty lists blocks([A,B,C|Bs1], [D,E,F|Bs2], [G,H,I|Bs3]) :- % get the first square 3x3 all_distinct([A,B,C,D,E,F,G,H,I]), % it should contain different values blocks(Bs1, Bs2, Bs3). % recurse on the remaining lists % define a problem with some fixed values problem(1, [[_,_,_, _,_,_, _,_,_], [_,_,_, _,_,3, _,8,5], [_,_,1, _,2,_, _,_,_], [_,_,_, 5,_,7, _,_,_], [_,_,4, _,_,_, 1,_,_], [_,9,_, _,_,_, _,_,_], [5,_,_, _,_,_, _,7,3], [_,_,2, _,1,_, _,_,_], [_,_,_, _,4,_, _,_,9]]). % define a problem with some fixed values problem(2, [[_,_,_, _,_,_, _,_,_], [_,_,_, _,_,3, _,8,5], [_,_,1, _,2,_, _,_,_], [_,_,_, 6,_,7, _,_,_], [_,_,4, _,_,_, 1,_,_], [_,9,_, _,_,_, _,_,_], [5,_,_, _,_,_, _,7,3], [_,_,2, _,1,_, _,_,_], [_,_,_, _,4,_, _,_,8]]). /** ?- problem(1, Rows), sudoku(Rows). */