密码算术序言测试失败递归思想 [英] cryptarithmetic prolog test fails recursion idea
问题描述
我需要为二 + 二 = 四的密码算法测试这段代码,但它给了我错误的错误.我需要知道为什么会这样.它适用于 donald+robert=gerald 或 it+is=me.我知道递归是如何工作的,但由于我无法调试它,我不知道出了什么问题.
I need to test this code for crypt arithmetic for two + two = four but it is giving me false which is wrong. I need to know why is this happening. It works for donald+robert= gerald or it+is=me. I got the idea of how recursion works but since i cannot debug it I have no idea what is wrong.
sum(N1,N2,N) :-
sum1(N1,N2,N,0,0,[0,1,2,3,4,5,6,7,8,9], _).
sum1([], [], [], C,C,D,D).
sum1([D1|N1], [D2|N2], [D|N], CR, C, Digs1, Digs) :-
sum1(N1,N2,N, CR, CLN, Digs1, Digs2),
digsum(D1,D2, CLN, D, C, Digs2, Digs).
digsum(D1,D2, C1, D, C, Digs1, Digs) :-
del_var(D1, Digs1, Digs2),
del_var(D2, Digs2, Digs3),
del_var(D, Digs3, Digs),
S is D1+D2+C1,
D is S mod 10,
C is S // 10.
del_var(A,L,L) :-
nonvar(A), !.
del_var(A, [A|L], L).
del_var(A, [B|L], [B|L1]) :-
del_var(A,L,L1).
推荐答案
您的代码没有任何问题,只是它仅适用于相同长度的列表.这就是为什么它适用于 IT + IS = ME(长度为 2 的列表)和 DONALD + ROBERT = GERALD(长度为 6 的列表).实际上,很容易找到解决方法:例如,您可以使用前导零填充较短的列表.所以代替 sum([T,W,O], [T,W,O], [F,O,U,R])
你必须做类似 sum([0,T,W,O], [0,T,W,O], [F,O,U,R])
它将起作用.
There is nothing wrong with your code except that it works only for lists of same lenghts. That's why it works for IT + IS = ME (lists of length 2) and for DONALD + ROBERT = GERALD (lists of length 6). Actually, it is quite easy to find a workaround: for example you can fill shorter lists with leading zeros. So instead of sum([T,W,O], [T,W,O], [F,O,U,R])
you have to do something like sum([0,T,W,O], [0,T,W,O], [F,O,U,R])
and it will work.
这篇关于密码算术序言测试失败递归思想的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!