swi-prolog 解决数独

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

转载于:https://my.oschina.net/leopardsaga/blog/106290

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值