简体   繁体   English

解决Prolog中的Kakuro拼图(5x5)

[英]Solving Kakuro puzzle (5x5) in Prolog

在此输入图像描述

Assuming that: 假如说:

A+B+C=24
E+F+G=11
J+K+L=22
N+O+P=14
A+E=17
B+F+J+N=26
C+G+K+O=15
L+P=13

How could i find a possible solution to the problem, given the constraints above, using the predicate solve/1 ? 考虑到上述约束,使用谓词solve/1 ,我怎样才能找到问题的可能解决方案? My first attempt was below, with no result. 我的第一次尝试是在下面,没有结果。 Thanks in advance! 提前致谢!

solve(L1) :-
    L1 = [A,B,C,E,F,G,J,K,L,N,O,P],
    A is 24-B-C,
    B is 26-F-J-N,
    C is 15-G-K-O,
    E is 11-F-G,
    E is 17-A,
    J is 22-K-L,
    N is 14-O-P,
    L is 13-P,
    write(L1).

As @lurker already said in his comment, use CLP(FD) constraints . 正如@lurker在评论中已经说过的那样,使用CLP(FD)约束

In addition, I recommend: 另外,我建议:

  1. instead of solve/1 , use a declarative name like solution/1 . 而不是solve/1 ,使用像solution/1这样的声明性名称 You should describe what holds for a solution, so that the relation makes sense in all directions, also for example if the solution is already given and you want to validate it. 您应该描述的解决方案是什么使人,这样的关系在各个方向上是有道理的,还例如,如果解决方案已经给出要验证它。
  2. By convention, it makes sense to let variables that stand for lists end with an s . 按照惯例,让代表列表的变量以s结尾是有意义s
  3. Separate side-effects from pure code. 与纯代码分开的副作用。 In fact, remove side-effects altogether. 事实上,完全消除副作用。 Let the do the printing for you! 为您做印刷!

For example: 例如:

:- use_module(library(clpfd)).

solution(Ls) :-
    Ls = [A,B,C,E,F,G,J,K,L,N,O,P],
    A #= 24-B-C,
    B #= 26-F-J-N,
    C #= 15-G-K-O,
    E #= 11-F-G,
    E #= 17-A,
    J #= 22-K-L,
    N #= 14-O-P,
    L #= 13-P.

This already works for queries like: 这已经适用于以下查询:

?- solution(Ls), Ls ins 0..sup, label(Ls).
Ls = [6, 3, 15, 11, 0, 0, 9, 0, 13, 14, 0, 0] ;
Ls = [6, 3, 15, 11, 0, 0, 10, 0, 12, 13, 0, 1] ;
Ls = [6, 3, 15, 11, 0, 0, 11, 0, 11, 12, 0, 2] ;
etc.

I leave completing this as an easy exercise. 我完成这个作为一个简单的练习。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM