密码运算

Cryptarithmetic operation

我正在尝试为 "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 ] ;

谢谢。

如果您想要格式化的输出与 Prolog 提供的答案不同,我建议您将实际关系与输出完全分开。因此,让我们从谓词 puzzle/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]).

写一个处理输出的谓词。按照您的所需输出示例,可能类似于输出查询,然后是变量替换,每行一个,最后是输入方程式,其中字母被数字替换为解决难题的数字(这正是您版本的最后一个目标puzzle/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 的第一个目标生成的输出。