From 6f68e1818229e0d2dad760062e6b5bb137b88f5b Mon Sep 17 00:00:00 2001 From: zhang Date: Sun, 23 Jan 2022 12:42:38 +0800 Subject: =?UTF-8?q?=E9=9A=8F=E6=9C=BA=E6=B8=B8=E8=B5=B0=20&=20ortools=20de?= =?UTF-8?q?mo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ordemo/send_more_money.py | 54 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 ordemo/send_more_money.py (limited to 'ordemo/send_more_money.py') diff --git a/ordemo/send_more_money.py b/ordemo/send_more_money.py new file mode 100644 index 0000000..77fddda --- /dev/null +++ b/ordemo/send_more_money.py @@ -0,0 +1,54 @@ + +from ortools.sat.python import cp_model + + +# https://developers.google.com/optimization/cp/cryptarithmetic + +class VarArraySolutionPrinter(cp_model.CpSolverSolutionCallback): + """Print intermediate solutions.""" + + def __init__(self, variables): + cp_model.CpSolverSolutionCallback.__init__(self) + self.__variables = variables + self.__solution_count = 0 + + def on_solution_callback(self): + self.__solution_count += 1 + for v in self.__variables: + print('%s=%i' % (v, self.Value(v)), end=' ') + print() + + def solution_count(self): + return self.__solution_count + + +model = cp_model.CpModel() + +base = 10 + +# SEND + MORE = MONEY +S = model.NewIntVar(1, base-1, 'S') +M = model.NewIntVar(1, base-1, 'M') + +E = model.NewIntVar(0, base-1, 'E') +N = model.NewIntVar(0, base-1, 'N') +D = model.NewIntVar(0, base-1, 'D') +O = model.NewIntVar(0, base-1, 'O') +R = model.NewIntVar(0, base-1, 'R') +Y = model.NewIntVar(0, base-1, 'Y') + +letters = [S, M, E, N, D, O, R, Y] + +model.AddAllDifferent(letters) +model.Add(S*base**3 + E*base**2 + N*base + D + + M*base**3 + O*base**2 + R*base + E + == M*base**4 + O*base**3 + N*base**2 + E*base + Y) + +solver = cp_model.CpSolver() +solution_printer = VarArraySolutionPrinter(letters) +solver.parameters.enumerate_all_solutions = True + +solver.Solve(model, solution_printer) + +print( + f" {solver.Value(S)}{solver.Value(E)}{solver.Value(N)}{solver.Value(D)}\n+ {solver.Value(M)}{solver.Value(O)}{solver.Value(R)}{solver.Value(E)}\n={solver.Value(M)}{solver.Value(O)}{solver.Value(N)}{solver.Value(E)}{solver.Value(Y)}") -- cgit v1.2.3