From New Scientist #3492, 25th May 2024 [link] [link]
If we use the digits 0-9 in place of the letters A–J (in some order) in the numbers ABC, DE, FGH and IJ, we can create four numbers to use in calculations. For example, the numbers could be 134, 50, 289 and 67; or 013, 56, 289 and 74.
(a) What is the largest total you can make for ABC + DE + FGH + IJ by assigning the digits?
(b) Can you assign the digits to maximise the value of (ABC × DE) + (FGH × IJ)? What is the largest total you can get?
(c) How can you assign the digits to make the value of (ABC × DE) − (FGH × IJ) as close to zero as possible?
[braintwister21]
We can provide a brute force solution for these puzzles using the [[
SubstitutedExpression
]] solver from the enigma.py library. (Although it is not necessarily very fast – 100ms for part (a), and 3.88s each for parts (b) and (c)).Note that the puzzle permits leading zeros (as in the second example).
For (a) it doesn’t matter what order the digits appear in each column:
(a) The largest value is 1926:
Not unsurprisingly, 8 and 9 are in the hundreds column. 4, 5, 6, 7 in the tens column. And 0, 1, 2, 3 in the units column.
(b) The largest value is 125354:
Again, the larger digits tend to be leading digits, and smaller digits towards the end.
(c) There are 99 ways we can get a value of 0. One of them is:
The following Python program examines all possible letter to digit assignments, and solves all three parts of the puzzle in 215ms (under PyPy 7.3.16).
To avoid repeating code, as only one solve statement is allowed in MiniZinc, I have had to comment out two of the three solve/output statements to show the third part e.g. as shown, the solution finds Part(b) answer, with Part(a) and Part(c) commented out.
I also found 10 solutions for part (c) with a difference of 1, the last one being (703 * 82) – (945 * 61).
Pure brute force solution for all three parts:
Same solution as shown above.
Runtimes:
Dell XPS13 i7: 287 s
iPhone 14 mini: 240 s
iPad Pro 11″ M4: 130 s
Windows 10 (i3): 247s / 22s for CPython / PyPy.
It’s good to know that PyPy is here so much faster.
In my professional simulation life (see salabim.org), I have found that PyPy is often even slower than CPython!
I also did some count on the number of solutions:
a) 1152 solutions
b) 4 solutions
c) 198 solutions (no idea why @Jim Randell comes to 99)
@Ruud: For (c) the solutions come in pairs as every solution gives another symmetrical solution with the values A/F, B/G, C/H, D/I, E/J can be swapped over, so I only counted one from each pair.
Counting separate assignments of symbols to digits you would get twice the number, i.e. 198 solutions (or 128 if you disallow leading zeros – from 64 pairs).
There are no solutions involving leading zeros for the parts (a) and (b).
This program runs in 65/130 ms for PyPy/CPython.