A kryptarithm - this is an example of arithmetic, in which all or some of the digits are replaced by letters. The rule must be satisfied: the different letters represent different digits, the identical letters represent the identical digits. See the link  http://en.wikipedia.org/wiki/Verbal_arithmetic.

The following procedure, called  Ksolve , solves kryptarithms in which are used four operations (addition, subtraction, multiplication and division). In the procedure Acer's  procedure  MyHandler is  used, which prevents the program to stop in case of 0 in the denominator.

Ksolve:=proc(A)

local MyHandler, L, m, M, S, T, L1, n, L2, N, P, R, i, L3, B, R1, R2;

   uses combinat, ListTools;

   MyHandler := proc(operator,operands,default_value)

      NumericStatus( division_by_zero = false );

      return infinity;

   end proc;

   NumericEventHandler(division_by_zero=MyHandler);

   L:=indets(A); m:=nops(L);

   assign(seq(M[i]=convert(L[i], string), i=1..nops(L)));

   S:=[seq([seq(M[i][j], j=1..length(M[i]))] , i=1..nops(L))];

   T:=select(x->type(parse(x),symbol),convert(Flatten(S), set));

   L1:=map(x->map(parse,x), T);  n:=nops(L1);

   L2:=map(x->map(parse,x), S);  N:=[seq(nops(L2[k]), k=1..nops(L2))];

   P:=permute({k $ k=0..9},nops(L1)); R:=[]:

   for i in P do

      L3:=eval(L2, [seq(L1[k]=i[k], k=1..n)]);

      B:=eval(A, [seq(L[k]=add(L3[k][s]*10^(N[k]-s), s=1..N[k]), k=1..m)]);

      if B then R:=[op(R), L3] fi;

   od;

   R1:=remove(x->convert([seq(x[i,1]=0 and nops(x[i])>1, i=1..nops(x))], `or`), R);

   R2:=[seq([seq(add(R1[i,j,k]*10^(nops(R1[i,j])-k), k=1..nops(R1[i,j])), j=1..nops(R1[i]))],    i=1..nops(R1))];

   seq(eval(A,[seq(L[j]=convert(R2[i,j], symbol), j=1..nops(L))]), i=1..nops(R2));

end proc;

 

When using the procedure if  the coded number begins with a digit and  contains a letter, it must be specified in back quotes else an error will be detected.

 

Two classic examples:

Ksolve(SEND + MORE = MONEY);                         

                              9567 + 1085 = 10652

Ksolve(SATURN + URANUS + NEPTUNE + PLUTO = PLANETS);

            127503 + 502351 + 3947539 + 46578 = 4623971

 

Some my examples:

Ksolve(2*apple + 3*pear = 5*fruit);                     

                           2*25508 + 3*5823 = 5*13697

Ksolve(`1abc`  + cbac = aecd);                         

                                  1583 + 3853 = 5436

Ksolve(a1a/bb=c);

                                616/77 = 8, 616/88 = 7

 

Kriptarithms.mws                           


Please Wait...