Extra material: Cryptarithms puzzle
The July 1924 issue of the famous British magazine The Strand included a word puzzle by Henry E. Dudeney in his regular contribution "Perplexities". The puzzle is to assign a unique digit to each letter appearing in the equation
such that the arithmetic equation is satisfied, and the leading digit for M is non-zero. There are many more examples of these puzzles, but this is perhaps the most well-known.
Preamble: Install Pyomo and a solver
The following cell sets and verifies a global SOLVER for the notebook. If run on Google Colab, the cell installs Pyomo and the HiGHS solver, while, if run elsewhere, it assumes Pyomo and HiGHS have been previously installed. It then sets to use HiGHS as solver via the appsi module and a test is performed to verify that it is available. The solver interface is stored in a global object SOLVER for later use.
Modeling and Solution
There are several possible approaches to modeling this puzzle in Pyomo.
One approach would be to using a matrix of binary variables indexed by letter and digit such that designates the corresponding assignment. The problem constraints can then be implemented by summing the binary variables along the two axes. The arithmetic constraint becomes a more challenging.
Another approach is to use Pyomo integer variables indexed by letters, then set up a linear expression to represent the puzzle. If we use the notation to represent the digit assigned to letter , the algebraic constraint becomes
The requirement that no two letters be assigned the same digit can be represented as a disjunction. Letting and denote the integers assigned to letters and , the disjunction becomes
Suggested exercises
Pyomo includes a logic-based solver
GDPoptfor generalized disjunctive programming problems. Implement and testGDPoptusing combinations of solution strategies and MIP solvers. Compare the performance ofGDPoptto the constraint solvergecode.There are many more examples of cryptarithm puzzles. Refactor this code and create a function that can be used to solve generic puzzles of this type.