:- use module(library(clpfd)). sudoku(Rs) :- flatten(Rs,Vs), Vs ins 1 .. 9, rows(Rs), columns(Rs), blocks(Rs), label(Vs), maplist(writeln,Rs).
rows(Rs) :- maplist(all distinct,Rs).
columns(Rs) :- columns(9,Rs). columns(0,Rs). columns(N,Rs) :- N > 0, N1 is N-1, maplist(nth0(N1),Rs,X), all distinct(X), columns(N1,Rs).
blocks([A,B,C,D,E,F,G,H,I]) :- blocks(A,B,C), blocks(D,E,F), blocks(G,H,I). blocks([],[],[]). blocks([A,B,C|Bs1],[D,E,F|Bs2],[G,H,I|Bs3]) :- all distinct([A,B,C,D,E,F,G,H,I]), blocks(Bs1,Bs2,Bs3).
If any of the possible values of a cell is not possible in any of the other conflicting cell than its safe to assume that, that value is the value of this cell.
hope its not confused. check the line 313 to 386 of my code.
1. Construct a 9x9 Array of possibility arrays containing the numbers 1-9. 2. When a possibility array is reduced to 1 element, remove this number from all related arrays (row, column, box). 3. Reduce the arrays to 1 number as specified by the initial puzzle. 4. If, after propagation all possibility arrays have 1 item, the puzzle is solved 5. Otherwise,choose one of the shortest possiblity arrays and try a value, backtrack if this leads to an unsolvable puzzle
The key points are the memoisation of possiblities, and choosing cells with the smallest number of possibilities for the search.
I put the results on github a while back: http://github.com/AnthonySteele/SudokuSolver/blob/master/Sud...
IMHO the fact that it's fast and not very complex to brute-force Sudoku makes it a lot less interesting as a puzzle for people to solve.