在prolog中解决难题 - 生成具有约束的解决方案?

时间:2016-04-07 12:35:53

标签: prolog clpfd

我正在尝试使用prolog来尝试解决kakuro难题。我有一个这样的规则列表,其中R和C代表每个框的行和起点,L代表长度,S是行中数字的总和,

 % across(R, C, L, S)
 across(2,4,2,4).
 across(2,10,2,4).  
 across(3,4,4,12).
 across(3,10,2,6).
 across(4,3,2,6).

据我所知,为了解决使用约束的难题,对于每个元素L,我必须找到1到9之间的不同数字,当加起来时它们等于S.我真的很挣扎为了解决这个问题,我到目前为止的代码是:

solveAcross(Solution) :-
    findall([R,C,L,S], across(R,C,L,S), List), 
    Solution = length(List, L),
    Solution ins 1..9,
    all_distinct(Solution),
    labeling([], Solution).

但这一切都是假的。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

所以首先你需要创建你的矩阵,这将最终成为你的kakuro拼图的网格。这绝对是第一步 - 如果你已经成功了,那就道歉了。

然后你想为跨约束制定一些规则:

acrossConstraints(Matrix) :- getAcross(List), applyAcross(Matrix,List).
%this is the overall thing to call, containing two predicates you need to make
getAcross :- findall([R,C,L,S],across(R,C,L,S),List).
%creates a list of the across facts
applyAcross(Matrix,[[R,C,L,S]|T]) :- acrossConstraints(R,C,L,S,M), applyAcross(Matrix,T). 
%call another rule and recurse over the list.

acrossConstraints是棘手的一点 - 在这里你想要抓住你想要的方格,然后从那一点开始制作一个列表。提示:使用追加和提示。

祝你好运!