我正在学习《七周七种语言》,我只是想从书中找到一个例子。它解决迷你数独网格 (4x4)。
作者使用的是 gprolog,但我使用的是 swi-prolog(无论出于何种原因,我都无法让 gprolog 在我的虚拟机上工作,但 swi-prolog 第一次尝试就可以工作)。
我正在 VirtualBox 4.0.4 r70112 中运行 Ubuntu 10.04(希望这不是太相关!)
这是我的序言文件中的代码:
:- 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]).
我(故意)更改的唯一部分是:
- adding
use_module(library(clpfd)).
在顶部
- 改变
fd_all_different(Head),
to all_different(Head),
- 改变
fd_domain(Puzzle, 1, 4),
to Puzzle ins 1..4,
这是来自 swipl 的调用
?- sudoku([_, _, 2, 3,
_, _, _, _,
_, _, _, _,
3, 4, _, _],
Solution).
Solution = [4, 1, 2, 3, 2, 3, 4, 1, 1|...] ;
false.
该解在它中断之前都是正确的,此时序言似乎确定没有解。但是还有:
4 1 2 3
2 3 4 1
1 2 3 4
3 4 1 2
我已经搜索了代码,寻找拼写错误或放错位置的列,但无法找到其来源。有任何想法吗?