valid([]).
valid([Head|Tail]) :-
fd_all_different(Head),
valid(Tail).
sudoku(Puzzle, Solution) :-
Solution = Puzzle,
Puzzle = [S11, S12, S13, S14,
S21, S22, S23, S24,
S31, S32, S33, S34,
S41, S42, S43, S44],
fd_domain(Solution, 1, 4),
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], 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]).
helo, 你在这里看到程序了么?^_^
看上去只有一些游戏的规则而已。
* 4 x 4
* 每行或列都是1-4
* 每行(列)没有重复值
然后prolog会通过我们给出的规则,推倒出它认为的正确的结果。
例如:
| ?- sudoku([_, _, 2, 3, _, _, _, _, _, _, _, _, 3, 4, _, _], Solution).
Solution = [4,1,2,3,2,3,4,1,1,2,3,4,3,4,1,2]
从某些方面来说,prolog是一种很神奇并且优美的语言。
如果使用prolog来解决一个问题,那程序员要做的并不是去找各种各样的算法,相反只是告诉prolog这个程序的规则(定理)就足够了。
通过这些规则,prolog会推导出它认为正确的结果。
prolog,作为一门面向逻辑的语言,真心足够强悍。