cryptarithmetic prolog test fails recursion idea

末鹿安然 提交于 2019-12-11 08:46:22

问题


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).

回答1:


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.



来源:https://stackoverflow.com/questions/23575795/cryptarithmetic-prolog-test-fails-recursion-idea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!