Blame | Last modification | View Log | RSS feed
/* ca2.pl
Cryptarithmetic:
forbids the same digit being used more than once */
ca(L) :- write(' S E N D M O R Y'),
L = [S,E,N,D,M,O,R,Y],
col( 0,D,E,Y,C1,L),
col(C1,N,R,E,C2,L),
col(C2,E,O,N,C3,L),
col(C3,S,M,O,C4,L),
col(C4,0,0,M, 0,L).
col(Ci,X,Y,Z,Co,L) :- carry(Ci),
free_digit(X,L),
free_digit(Y,L),
free_digit(Z,L),
carry(Co),
sum(Ci,X,Y,Z),
carry(Ci,X,Y,Co).
sum(Ci,X,Y,Z) :- Z is (Ci+X+Y) mod 10.
carry(Ci,X,Y,Z) :- Z is (Ci+X+Y) // 10.
digit(0).
digit(1).
digit(2).
digit(3).
digit(4).
digit(5).
digit(6).
digit(7).
digit(8).
digit(9).
carry(0).
carry(1).
free_digit(Dig,UsedList) :- var(Dig),
digit(X),
not_in(X,UsedList),
Dig = X.
free_digit(Dig,_) :- nonvar(Dig).
not_in(_,[]).
not_in(D,[H|T]) :- var(H), not_in(D,T).
not_in(D,[H|T]) :- nonvar(H), D \= H, not_in(D,T).