swi-prolog是prolog比较流行的一种实现,但话说prolog这货的语法还真不好理解,而且资料少,当年与LISP相抗衡,现在好像不怎么火了。在win7上折腾,还是没把命令行交互模式下的readline补全给搞明白,体验太差了。
事实与规则文件内容如下:
% 加载库--有限域的计算
:- use_module(library(clpfd)).
valid([]).
valid([Head|Tail]) :-
all_different(Head), % in the book, this is 'fd_all_different'
valid(Tail).
% beginning of sudoku rule itself
sudoku(Puzzle, Solution) :-
Solution = Puzzle,
Puzzle = [S11, S12, S13, S14,
S21, S22, S23, S24,
S31, S32, S33, S34,
S41, S42, S43, S44],
Puzzle ins 1..4, % in the book, this is 'fd_domain'
Row1 = [S11, S12, S13, S14],
Row2 = [S21, S22, S23, S24],
Row3 = [S31, S32, S33, S34],
Row4 = [S41, S42, S43, S44],
Col1 = [S11, S21, S31, S41],
Col2 = [S12, S22, S32, S42],
Col3 = [S13, S23, S33, S43],
Col4 = [S14, S24, S34, S44],
Square1 = [S11, S12, S21, S22],
Square2 = [S13, S14, S23, S24],
Square3 = [S31, S32, S41, S42],
Square4 = [S33, S34, S43, S44],
valid([Row1, Row2, Row3, Row4,
Col1, Col2, Col3, Col4,
Square1, Square2, Square3, Square4]).
查询语句如下:
sudoku([_, _, 2, 3,
_, _, _, _,
_, _, _, _,
3, 4, _, _],
Solution).
查询结果默认不完全显示:
Solution = [4, 1, 2, 3, 2, 3, 4, 1, 1|...]
要改变查询语句,
且在回答语句后,按'w'键(表示write),打开完全显示,才会完全显示答案:
sudoku([_, _, 2, 3, _, _, _, _,
_, _, _, _,
3, 4, _, _],
Solution); true.
Solution = [4, 1, 2, 3, 2, 3, 4, 1, 1, 2, 3, 4, 3, 4, 1, 2]
或者直接一步到位,根据下面图的逻辑:
sudoku([_, _, 2, 3,
_, _, _, _,
_, _, _, _,
3, 4, _, _],
Solution), write(Solution), fail.
这输出看得别扭,看不太明白swi-prolog的格式化输出函数,楼主只能结果放到Python中格式化输出看的。
参考:http://hyry.dip.jp/tech/book/page/prolog/intro_complex_query.html
http://stackoverflow.com/questions/5617126/mini-sudoku-solver-in-prolog-stops-partway-through