Subversion Repositories programming

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
107 ira 1
/* ca2.pl
2
   Cryptarithmetic:
3
   forbids the same digit being used more than once */
4
 
5
ca(L) :- write('     S  E  N  D  M  O  R  Y'),
6
         L = [S,E,N,D,M,O,R,Y],
7
         col( 0,D,E,Y,C1,L),
8
         col(C1,N,R,E,C2,L),
9
         col(C2,E,O,N,C3,L),
10
         col(C3,S,M,O,C4,L),
11
         col(C4,0,0,M, 0,L).
12
 
13
col(Ci,X,Y,Z,Co,L) :- carry(Ci),
14
                      free_digit(X,L),
15
                      free_digit(Y,L),
16
                      free_digit(Z,L),
17
                      carry(Co),
18
                      sum(Ci,X,Y,Z),
19
                      carry(Ci,X,Y,Co).
20
 
21
sum(Ci,X,Y,Z) :- Z is (Ci+X+Y) mod 10.
22
 
23
carry(Ci,X,Y,Z) :- Z is (Ci+X+Y) // 10.
24
 
25
digit(0).
26
digit(1).
27
digit(2).
28
digit(3).
29
digit(4).
30
digit(5).
31
digit(6).
32
digit(7).
33
digit(8).
34
digit(9).
35
 
36
carry(0).
37
carry(1).
38
 
39
free_digit(Dig,UsedList) :- var(Dig),
40
                            digit(X),
41
                            not_in(X,UsedList),
42
                            Dig = X.
43
free_digit(Dig,_) :- nonvar(Dig).
44
 
45
not_in(_,[]).
46
not_in(D,[H|T]) :- var(H), not_in(D,T).
47
not_in(D,[H|T]) :- nonvar(H), D \= H, not_in(D,T).
48