You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.8 KiB

  1. /* MONEY, a crypto-arithmetic puzzle */
  2. /* Written in GNU MathProg by Andrew Makhorin <mao@gnu.org> */
  3. /* This is the classic example of a crypto-arithmetic puzzle published
  4. in the Strand Magazine by Henry Dudeney:
  5. S E N D
  6. +
  7. M O R E
  8. ---------
  9. M O N E Y
  10. In this puzzle the same letters mean the same digits. The question
  11. is: how to replace all the letters with the respective digits that
  12. makes the calculation correct?
  13. The solution to this puzzle is:
  14. O = 0, M = 1, Y = 2, E = 5, N = 6, D = 7, R = 8, and S = 9.
  15. References:
  16. H. E. Dudeney, in Strand Magazine vol. 68 (July 1924), pp. 97, 214.
  17. (From Wikipedia, the free encyclopedia.) */
  18. set LETTERS := { 'D', 'E', 'M', 'N', 'O', 'R', 'S', 'Y' };
  19. /* set of letters */
  20. set DIGITS := 0..9;
  21. /* set of digits */
  22. var x{i in LETTERS, d in DIGITS}, binary;
  23. /* x[i,d] = 1 means that letter i is digit d */
  24. s.t. one{i in LETTERS}: sum{d in DIGITS} x[i,d] = 1;
  25. /* each letter must correspond exactly to one digit */
  26. s.t. alldiff{d in DIGITS}: sum{i in LETTERS} x[i,d] <= 1;
  27. /* different letters must correspond to different digits; note that
  28. some digits may not correspond to any letters at all */
  29. var dig{i in LETTERS};
  30. /* dig[i] is a digit corresponding to letter i */
  31. s.t. map{i in LETTERS}: dig[i] = sum{d in DIGITS} d * x[i,d];
  32. var carry{1..3}, binary;
  33. /* carry bits */
  34. s.t. sum1: dig['D'] + dig['E'] = dig['Y'] + 10 * carry[1];
  35. s.t. sum2: dig['N'] + dig['R'] + carry[1] = dig['E'] + 10 * carry[2];
  36. s.t. sum3: dig['E'] + dig['O'] + carry[2] = dig['N'] + 10 * carry[3];
  37. s.t. sum4: dig['S'] + dig['M'] + carry[3] = dig['O'] + 10 * dig['M'];
  38. s.t. note: dig['M'] >= 1; /* M must not be 0 */
  39. solve;
  40. /* solve the puzzle */
  41. display dig;
  42. /* and display its solution */
  43. end;