密码算术运算

时间:2017-11-03 08:37:28

标签: prolog clpfd prolog-toplevel cryptarithmetic-puzzle

我正在尝试为" SEND MODE MONEY"编写Prolog代码。到目前为止,我得到了以下内容:

:- use_module(library(clpfd)).

puzzle([S,E,N,D] + [M,O,R,E] = [M,O,N,E,Y]) :- 
   Vars = [S,E,N,D,M,O,R,Y], 
   Vars ins 0..9, 
   all_different(Vars), 
   S*1000 + E*100 + N*10 + D + M*1000 + O*100 + R*10 + E 
       #= M*10000 + O*1000 + N*100 + E*10 + Y, 
   M #\= 0, 
   S #\= 0,
   label([S,E,N,D,M,O,R,Y]),
   format('~s ~w ~s ~w ~s ~w ~s ~w ~s ~s ~s ~w ~s ~w ~s ~w ~s ~w ~s ~s ~s ~w ~s ~w ~s ~w ~s ~w ~s ~w ~s ~s',
        [ "[", S, ",", E, ",", N, ",", D, "]",
         "+", "[", M, ",", O, ",", R, ",", E, "]",
         "=", "[", M, ",", O, ",", N,  ",", E, ",", Y, "]", ";" ]).

输出如下:

?- puzzle([S,E,N,D] + [M,O,R,E] = [M,O,N,E,Y]).

[ 9 , 5 , 6 , 7 ] + [ 1 , 0 , 8 , 5 ] = [ 1 , 0 , 6 , 5 , 2 ] ;
S = 9,
E = 5,
N = 6,
D = 7,
M = 1,
O = 0,
R = 8,
Y = 2.

但是我想在最后打印清单而不是在开头我该怎么办?

我需要得到的输出是:

?- puzzle([S,E,N,D] + [M,O,R,E] = [M,O,N,E,Y]).
S = 9,
E = 5,
N = 6,
D = 7,
M = 1,
O = 0,
R = 8,
Y = 2.
[ 9 , 5 , 6 , 7 ] + [ 1 , 0 , 8 , 5 ] = [ 1 , 0 , 6 , 5 , 2 ] ;

谢谢。

1 个答案:

答案 0 :(得分:3)

如果您希望格式化输出与Prolog提供的答案不同,我建议将实际关系与输出完全分开。因此,让我们从谓词拼图/ 1中删除最后一个目标:

puzzle([S,E,N,D] + [M,O,R,E] = [M,O,N,E,Y]) :- 
   Vars = [S,E,N,D,M,O,R,Y], 
   Vars ins 0..9, 
   all_different(Vars), 
   S*1000 + E*100 + N*10 + D + M*1000 + O*100 + R*10 + E 
       #= M*10000 + O*1000 + N*100 + E*10 + Y, 
   M #\= 0, 
   S #\= 0,
   label([S,E,N,D,M,O,R,Y]).

编写一个处理输出的谓词。按照你想要的输出示例,可能是输出查询后跟变量替换,每行一个,最后是输入方程,字母由解码拼图的数字代替(这完全是最后一个目标)从您的拼图版本/ 1):

output([S,E,N,D] + [M,O,R,E] = [M,O,N,E,Y]) :-
   format('?- puzzle([S,E,N,D] + [M,O,R,E] = [M,O,N,E,Y]).~n'),
   format('S = ~d,~nE = ~d,~nN = ~d,~nD = ~d,~nM = ~d,~nO = ~d,~nR = ~d,~nY = ~d.~n',[S,E,N,D,M,O,R,Y]),
   format('~s ~w ~s ~w ~s ~w ~s ~w ~s ~s ~s ~w ~s ~w ~s ~w ~s ~w ~s ~s ~s ~w ~s ~w ~s ~w ~s ~w ~s ~w ~s ~s',[ "[", S, ",", E, ",", N, ",", D, "]",  "+", "[", M, ",", O, ",", R, ",", E, "]", "=", "[", M, ",", O, ",", N,  ",", E, ",", Y, "]", ";" ]).

然后你有一个没有参数的调用谓词,所以只生成你想要的输出:

puzzleout :-
   puzzle(X),
   output(X).

通过这种方式,您可以使用谓词来解决难题并且不做任何其他操作:

?- puzzle([S,E,N,D] + [M,O,R,E] = [M,O,N,E,Y]).
S = 9,
E = 5,
N = 6,
D = 7,
M = 1,
O = 0,
R = 8,
Y = 2 ;
false.

你还有一个谓词可以产生你想要的输出:

?- puzzleout.
?- puzzle([S,E,N,D] + [M,O,R,E] = [M,O,N,E,Y]).
S = 9,
E = 5,
N = 6,
D = 7,
M = 1,
O = 0,
R = 8,
Y = 2.
[ 9 , 5 , 6 , 7 ] + [ 1 , 0 , 8 , 5 ] = [ 1 , 0 , 6 , 5 , 2 ] ;
true ;
false.

请注意,第二行不是您输入的查询,而是由output / 1的第一个目标生成的输出。