summaryrefslogtreecommitdiff
path: root/ordemo
diff options
context:
space:
mode:
authorzhang <zch921005@126.com>2022-01-23 12:42:38 +0800
committerzhang <zch921005@126.com>2022-01-23 12:42:38 +0800
commit6f68e1818229e0d2dad760062e6b5bb137b88f5b (patch)
tree55ec8ad3f340d7a9d276b2e17641b8a9c1c52ae3 /ordemo
parent0451d59752f3b61a6f6dfdb56d1f431083be4c7d (diff)
随机游走 & ortools demo
Diffstat (limited to 'ordemo')
-rw-r--r--ordemo/__init__.py0
-rw-r--r--ordemo/channeling.py4
-rw-r--r--ordemo/send_more_money.py54
3 files changed, 58 insertions, 0 deletions
diff --git a/ordemo/__init__.py b/ordemo/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/ordemo/__init__.py
diff --git a/ordemo/channeling.py b/ordemo/channeling.py
new file mode 100644
index 0000000..b53e519
--- /dev/null
+++ b/ordemo/channeling.py
@@ -0,0 +1,4 @@
+
+from ortools.sat.python import cp_model
+
+model = cp_model \ No newline at end of file
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)}")