examples/money.mod
author Alpar Juttner <alpar@cs.elte.hu>
Mon, 06 Dec 2010 13:09:21 +0100
changeset 1 c445c931472f
permissions -rw-r--r--
Import glpk-4.45

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