sudoku(Rows) :- length(Rows, 9), maplist(same_length(Rows), Rows), maplist(row_booleans, Rows, BRows), maplist(booleans_distinct, BRows), transpose(BRows, BColumns), maplist(booleans_distinct, BColumns), BRows = [As,Bs,Cs,Ds,Es,Fs,Gs,Hs,Is], blocks(As, Bs, Cs), blocks(Ds, Es, Fs), blocks(Gs, Hs, Is). blocks([], [], []). blocks([N1,N2,N3|Ns1], [N4,N5,N6|Ns2], [N7,N8,N9|Ns3]) :- booleans_distinct([N1,N2,N3,N4,N5,N6,N7,N8,N9]), blocks(Ns1, Ns2, Ns3). booleans_distinct(Bs) :- transpose(Bs, Ts), maplist(card1, Ts). card1(Bs) :- sat(card([1],Bs)). row_booleans(Row, Bs) :- same_length(Row, Bs), maplist(cell_boolean, Row, Bs). cell_boolean(Num, Bs) :- length(Bs, 9), sat(card([1],Bs)), element(Num, Bs, 1).
Here is an example Soduku problem, taken from Donald Knuth's The Art of Computer Programming:
knuth(b, [[1,_,3,_,5,6,_,8,9], [5,9,7,3,8,_,6,1,_], [6,8,_,1,_,9,3,_,5], [9,5,6,_,3,1,8,_,7], [_,3,1,5,_,8,9,6,_], [2,_,8,9,6,_,1,5,3], [8,_,9,6,_,5,_,3,1], [_,6,5,_,1,3,2,9,8], [3,1,_,8,9,_,5,_,6]]).
?- knuth(b, Rows), sudoku(Rows), maplist(portray_clause, Rows). [1, 2, 3, 4, 5, 6, 7, 8, 9]. [5, 9, 7, 3, 8, 2, 6, 1, 4]. [6, 8, 4, 1, 7, 9, 3, 2, 5]. [9, 5, 6, 2, 3, 1, 8, 4, 7]. [7, 3, 1, 5, 4, 8, 9, 6, 2]. [2, 4, 8, 9, 6, 7, 1, 5, 3]. [8, 7, 9, 6, 2, 5, 4, 3, 1]. [4, 6, 5, 7, 1, 3, 2, 9, 8]. [3, 1, 2, 8, 9, 4, 5, 7, 6].
Here is an example Soduku problem, taken from Donald Knuth's The Art of Computer Programming:
Sample query and result: