问题
I'm writing a mini sudoku solver in Prolog. The sudoku consists of 4x4 fields, e.g.
_ _ 2 3
_ _ _ _
_ _ _ _
3 4 _ _
If the sudoku is has only one possible solution (as the sudoku above), my program works as expected. But if I replace at least one given field with a gap (e.g. by replacing 4 by _), the output of Prolog is like this:
[_#3(1:4),_#23(1:4),2,3.....
I guess "_#3(1:4)" means "take 1 or 4", but I want each solution in a separated, non-ambiguous list. This is my code:
sudoku(Puzzle,Solution):-
Puzzle=Solution,
fd_domain(Solution,1,4),
Puzzle=[S11,S12,S13,S14,
S21,S22,S23,S24,
S31,S32,S33,S34,
S41,S42,S43,S44],
fd_all_different([S11,S12,S13,S14]),
fd_all_different([S21,S22,S23,S24]),
fd_all_different([S31,S32,S33,S34]),
fd_all_different([S41,S42,S43,S44]),
fd_all_different([S11,S21,S31,S41]),
fd_all_different([S12,S22,S32,S42]),
fd_all_different([S13,S23,S33,S43]),
fd_all_different([S14,S24,S34,S44]),
fd_all_different([S11,S12,S21,S22]),
fd_all_different([S13,S14,S23,S24]),
fd_all_different([S31,S32,S41,S42]),
fd_all_different([S33,S34,S43,S44]).
When I loaded it into Gnu Prolog, I type the following query:
sudoku([_,_,2,3,_,_,_,_,_,_,_,_,3,_,_,_],Sol).
What am I doing wrong?
回答1:
your Prolog is advising you of multiple solution, showing the residual constraints in store. You need to label the variables, i.e. let the engine enumerate valid values.
?- sudoku([_,_,2,3,_,_,_,_,_,_,_,_,3,_,_,_],Sol),fd_labeling(Sol).
Sol = [1,4,2,3,2,3,1,4,4,1,3,2,3,2,4,1] ? ;
Sol = [1,4,2,3,2,3,1,4,4,2,3,1,3,1,4,2] ? ;
Sol = [1,4,2,3,2,3,4,1,4,1,3,2,3,2,1,4] ? ;
Sol = [4,1,2,3,2,3,1,4,1,4,3,2,3,2,4,1] ? ;
Sol = [4,1,2,3,2,3,4,1,1,2,3,4,3,4,1,2] ? ;
Sol = [4,1,2,3,2,3,4,1,1,4,3,2,3,2,1,4]
来源:https://stackoverflow.com/questions/14912929/prolog-ambiguous-output