alpar@9: /* MONEY, a crypto-arithmetic puzzle */ alpar@9: alpar@9: /* Written in GNU MathProg by Andrew Makhorin */ alpar@9: alpar@9: /* This is the classic example of a crypto-arithmetic puzzle published alpar@9: in the Strand Magazine by Henry Dudeney: alpar@9: alpar@9: S E N D alpar@9: + alpar@9: M O R E alpar@9: --------- alpar@9: M O N E Y alpar@9: alpar@9: In this puzzle the same letters mean the same digits. The question alpar@9: is: how to replace all the letters with the respective digits that alpar@9: makes the calculation correct? alpar@9: alpar@9: The solution to this puzzle is: alpar@9: O = 0, M = 1, Y = 2, E = 5, N = 6, D = 7, R = 8, and S = 9. alpar@9: alpar@9: References: alpar@9: H. E. Dudeney, in Strand Magazine vol. 68 (July 1924), pp. 97, 214. alpar@9: alpar@9: (From Wikipedia, the free encyclopedia.) */ alpar@9: alpar@9: set LETTERS := { 'D', 'E', 'M', 'N', 'O', 'R', 'S', 'Y' }; alpar@9: /* set of letters */ alpar@9: alpar@9: set DIGITS := 0..9; alpar@9: /* set of digits */ alpar@9: alpar@9: var x{i in LETTERS, d in DIGITS}, binary; alpar@9: /* x[i,d] = 1 means that letter i is digit d */ alpar@9: alpar@9: s.t. one{i in LETTERS}: sum{d in DIGITS} x[i,d] = 1; alpar@9: /* each letter must correspond exactly to one digit */ alpar@9: alpar@9: s.t. alldiff{d in DIGITS}: sum{i in LETTERS} x[i,d] <= 1; alpar@9: /* different letters must correspond to different digits; note that alpar@9: some digits may not correspond to any letters at all */ alpar@9: alpar@9: var dig{i in LETTERS}; alpar@9: /* dig[i] is a digit corresponding to letter i */ alpar@9: alpar@9: s.t. map{i in LETTERS}: dig[i] = sum{d in DIGITS} d * x[i,d]; alpar@9: alpar@9: var carry{1..3}, binary; alpar@9: /* carry bits */ alpar@9: alpar@9: s.t. sum1: dig['D'] + dig['E'] = dig['Y'] + 10 * carry[1]; alpar@9: s.t. sum2: dig['N'] + dig['R'] + carry[1] = dig['E'] + 10 * carry[2]; alpar@9: s.t. sum3: dig['E'] + dig['O'] + carry[2] = dig['N'] + 10 * carry[3]; alpar@9: s.t. sum4: dig['S'] + dig['M'] + carry[3] = dig['O'] + 10 * dig['M']; alpar@9: s.t. note: dig['M'] >= 1; /* M must not be 0 */ alpar@9: alpar@9: solve; alpar@9: /* solve the puzzle */ alpar@9: alpar@9: display dig; alpar@9: /* and display its solution */ alpar@9: alpar@9: end;