【发布时间】:2015-11-10 17:33:44
【问题描述】:
我正在学习 Prolog。我正在做一个任务。我已经生成了一些代码,这些代码部分有效。但是,不知何故,它给出了多个重复的答案。
问题是:
% Every letter represents a Digit (0,...,9).
% Leading digits (S and M) can not be 0.
% S E N D
% + M O R E
% ---------
% M O N E Y
% Write a Prolog program that solves the quiz, i.e., that finds the
% appropriate values for S,E,N,D,M,O, ... such that the addition is correct.
我想出的解决方案是:
jobs1([0,1,2,3,4,5,6,7,8,9]).
solution1([_,_,S,E,N,D,M,O,R,Y],
constraints([
\+ S is 0,
\+ M is 0,
0 is (10000*M+1000*O+100*N+10*E+Y - (1000*S+100*E+10*N+D + 1000*M+100*O+10*R+E)) ])).
puzzle1(Erg) :- write("Puzzle1 "), nl, jobs1(S),
solution1([_,_|Erg] ,
constraints(Cs)),permC(S,[_,_|Erg],Cs) .
但是,当我运行这段代码时,我会得到这样的答案:
7 ?- puzzle1(S).
Puzzle1
S = [9, 5, 6, 7, 1, 0, 8, 2] ;
S = [9, 5, 6, 7, 1, 0, 8, 2] ;
我知道为什么会发生这种情况(因为,我忽略了前 2 个位置,并且由于它们的排列,结果显示为 2 次)。您能否帮助了解如何在不使用 ! 的情况下将其删除(因为,如果有多个答案, ! 只会显示第一个答案,这不是预期的。)
提前致谢!
【问题讨论】:
-
为什么
solution1的第一个参数中有前导_? -
因为我必须将 0,1,...9 分配给字符 S、E、N、D、M、O、R、Y。所以,我不得不把 _ , _ 放在那里。否则程序返回false。
-
permC/3的定义是什么样的? -
如何防止多余的答案? 使用clpfd! 引用swi-prolog.org/man/clpfd.html:“标签总是完整的,总是终止的,并且不会产生多余的解决方案。”
标签: prolog clpfd cryptarithmetic-puzzle