1 //
2 // Copyright 2012 Hakan Kjellerstrand
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //     http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 
16 using System;
17 using Google.OrTools.ConstraintSolver;
18 
19 public class SendMoreMoney
20 {
21     /**
22      *
23      * Solve the SEND+MORE=MONEY problem
24      *
25      */
Solve()26     private static void Solve()
27     {
28         Solver solver = new Solver("SendMoreMoney");
29 
30         //
31         // Decision variables
32         //
33         IntVar S = solver.MakeIntVar(0, 9, "S");
34         IntVar E = solver.MakeIntVar(0, 9, "E");
35         IntVar N = solver.MakeIntVar(0, 9, "N");
36         IntVar D = solver.MakeIntVar(0, 9, "D");
37         IntVar M = solver.MakeIntVar(0, 9, "M");
38         IntVar O = solver.MakeIntVar(0, 9, "O");
39         IntVar R = solver.MakeIntVar(0, 9, "R");
40         IntVar Y = solver.MakeIntVar(0, 9, "Y");
41 
42         // for AllDifferent()
43         IntVar[] x = new IntVar[] { S, E, N, D, M, O, R, Y };
44 
45         //
46         // Constraints
47         //
48         solver.Add(x.AllDifferent());
49         solver.Add(S * 1000 + E * 100 + N * 10 + D + M * 1000 + O * 100 + R * 10 + E ==
50                    M * 10000 + O * 1000 + N * 100 + E * 10 + Y);
51 
52         solver.Add(S > 0);
53         solver.Add(M > 0);
54 
55         //
56         // Search
57         //
58         DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE);
59 
60         solver.NewSearch(db);
61         while (solver.NextSolution())
62         {
63             for (int i = 0; i < 8; i++)
64             {
65                 Console.Write(x[i].ToString() + " ");
66             }
67             Console.WriteLine();
68         }
69 
70         Console.WriteLine("\nWallTime: " + solver.WallTime() + "ms ");
71         Console.WriteLine("Failures: " + solver.Failures());
72         Console.WriteLine("Branches: " + solver.Branches());
73 
74         solver.EndSearch();
75     }
76 
Main(String[] args)77     public static void Main(String[] args)
78     {
79         Solve();
80     }
81 }
82