Introduction
A cryptarithmetic puzzle is a mathematical puzzle in which letters represent digits and the goal is to find the digit assignment that makes a given arithmetic equation true. The most famous example is SEND + MORE = MONEY, where each letter is a unique digit and the equation is a valid addition. The puzzle was popularized by the English mathematician Henry Dudeney in 1924 in his puzzle column in the Strand Magazine. In this cryptarithmetic puzzle solver java tutorial we will implement a complete solver using backtracking.
Cryptarithmetic puzzles matter historically as one of the earliest constraint satisfaction problems studied in computer science. They were popular in recreational mathematics in the late 19th and early 20th centuries, with solvers including Lewis Carroll (author of Alice in Wonderland) and Alan Turing (founder of computer science). The puzzles teach the fundamental concepts of search, backtracking, and constraint propagation that underlie modern artificial intelligence.
What is a Cryptarithmetic Puzzle?
A cryptarithmetic puzzle is a constraint satisfaction problem in which each letter in the puzzle represents a unique digit from 0 to 9. The puzzle is to find a digit assignment that makes the given arithmetic equation true. The constraints are: (1) each letter maps to a unique digit, (2) the leading digit of each word cannot be zero (because then it would not be a "leading" digit), and (3) the arithmetic equation must be satisfied.
For example, the SEND + MORE = MONEY puzzle has 8 distinct letters: S, E, N, D, M, O, R, Y. The constraints are that S and M cannot be 0, all 8 letters must have distinct digit values, and the equation SEND + MORE = MONEY must be true when the letters are replaced by their digits.
The unique solution to this puzzle is S=9, E=5, N=6, D=7, M=1, O=0, R=8, Y=2, which gives 9567 + 1085 = 10652. This is a valid arithmetic equation, so the solution is correct.
Compared to brute force (which would try all 10^8 = 100 million assignments), backtracking search is much more efficient. By pruning branches that violate the constraints early, we can find the solution in a fraction of the search space.
How Cryptarithmetic Solving Works Step by Step
Suppose we want to solve SEND + MORE = MONEY.
Step 1: Identify the unique letters. The puzzle has 8 letters: S, E, N, D, M, O, R, Y.
Step 2: Identify the leading letters (which cannot be 0). S and M are leading letters, so they cannot be 0.
Step 3: Set up the constraint: 1000*S + 100*E + 10*N + D + 1000*M + 100*O + 10*R + E = 10000*M + 1000*O + 100*N + 10*E + Y.
Step 4: Use backtracking to assign digits to letters one at a time. At each step, check whether the partial assignment is consistent (no letter has the same digit as another). If we reach a complete assignment, check whether the equation is satisfied. If yes, we have a solution. If no, backtrack and try a different assignment.
Step 5: With efficient pruning, the backtracking search will find the unique solution S=9, E=5, N=6, D=7, M=1, O=0, R=8, Y=2, which gives 9567 + 1085 = 10652.
Java Program to Solve Cryptarithmetic Puzzles
import java.util.*;
public class CryptarithmeticSolver {
static Map<Character, Integer> assignment = new HashMap<>();
static List<Character> letters;
static String word1, word2, result;
public static long wordToNumber(String word) {
long value = 0;
for (int i = 0; i < word.length(); i++) {
int d = assignment.get(word.charAt(i));
value = value * 10 + d;
}
return value;
}
public static boolean isSolution() {
long n1 = wordToNumber(word1);
long n2 = wordToNumber(word2);
long r = wordToNumber(result);
return n1 + n2 == r;
}
public static boolean leadingNonZero(String word) {
char first = word.charAt(0);
return assignment.get(first) != 0;
}
public static boolean solve(int index) {
if (index == letters.size()) {
if (leadingNonZero(word1) && leadingNonZero(word2) && leadingNonZero(result)) {
return isSolution();
}
return false;
}
char letter = letters.get(index);
for (int digit = 0; digit < 10; digit++) {
if (assignment.containsValue(digit)) continue;
assignment.put(letter, digit);
if (solve(index + 1)) return true;
assignment.remove(letter);
}
return false;
}
public static List<Character> uniqueLetters(String... words) {
Set<Character> seen = new LinkedHashSet<>();
for (String w : words) {
for (int i = 0; i < w.length(); i++) {
seen.add(w.charAt(i));
}
}
return new ArrayList<>(seen);
}
public static void solve(String w1, String w2, String r) {
word1 = w1.toUpperCase();
word2 = w2.toUpperCase();
result = r.toUpperCase();
letters = uniqueLetters(word1, word2, result);
assignment.clear();
System.out.println("Puzzle: " + word1 + " + " + word2 + " = " + result);
System.out.println("Letters: " + letters);
if (solve(0)) {
System.out.println("Solution found:");
for (Map.Entry<Character, Integer> e : assignment.entrySet()) {
System.out.println(" " + e.getKey() + " = " + e.getValue());
}
System.out.println("Verification: " + wordToNumber(word1) + " + " + wordToNumber(word2) + " = " + wordToNumber(result));
} else {
System.out.println("No solution found.");
}
}
public static void main(String[] args) {
solve("SEND", "MORE", "MONEY");
}
}
Code Explanation Line by Line
The assignment map stores the current digit assignment for each letter. The letters list contains all unique letters in the order they were first encountered. The word1, word2, and result strings hold the three operands of the addition.
The wordToNumber method converts a word to its numeric value by reading the digits from left to right and accumulating them as a base-10 number. For each letter, we look up its assigned digit and add it to the running total. The result is the numeric value of the word given the current assignment.
The isSolution method checks whether the current assignment satisfies the equation. We compute the numeric values of all three words and check whether word1 + word2 equals result. If yes, we have a valid solution.
The leadingNonZero method checks whether the first letter of a word is assigned a non-zero digit. This enforces the constraint that leading digits cannot be zero (because then the word would have fewer digits than its length implies).
The solve method is the heart of the backtracking search. At each call, we either have a complete assignment (in which case we check if it is a solution) or we try to assign a digit to the current letter. We iterate through all digits 0 to 9, skipping any that are already in use. For each candidate digit, we make the assignment and recursively solve the next letter. If the recursive call returns true, we have found a solution and propagate the success upward. Otherwise, we backtrack by removing the assignment and trying the next digit.
The uniqueLetters method extracts all unique letters from the input words in the order they are first encountered. We use a LinkedHashSet to preserve order while ensuring uniqueness, then convert to a List for indexed access.
The solve (public) method sets up the puzzle and initiates the search. It prints the puzzle, the list of letters, and the solution (if found) or a message saying no solution was found.
Sample Input and Output
Puzzle: SEND + MORE = MONEY Letters: [S, E, N, D, M, O, R, Y] Solution found: S = 9 E = 5 N = 6 D = 7 M = 1 O = 0 R = 8 Y = 2 Verification: 9567 + 1085 = 10652
The output shows the unique solution to the SEND + MORE = MONEY puzzle. The verification line confirms that the assignment makes the equation true: 9567 + 1085 = 10652.
Common Mistakes to Avoid
1. Forgetting the leading non-zero constraint. If the first letter of a word is assigned 0, the word would have fewer digits than its length implies, which is incorrect. Always check leadingNonZero before accepting a solution.
2. Using inefficient pruning. The naive approach of generating all 10^8 assignments and checking each is too slow. Backtracking with early pruning reduces the search space by orders of magnitude.
3. Forgetting to check that letters have distinct digits. The constraint that each letter has a unique digit is essential. Without it, the puzzle has many trivial solutions.
4. Modifying the assignment map during iteration. The recursive solve method modifies the global assignment map, which is fine, but be careful not to iterate over the map while it is being modified.
5. Confusing the order of letters. The uniqueLetters method preserves the order of first encounter, which is important for the backtracking search. Different orderings can lead to different search times, but the final answer is the same.
Real-World Applications
Cryptarithmetic puzzles have no direct security use, but they are foundational to constraint satisfaction problems in artificial intelligence. The same backtracking techniques used to solve cryptarithmetic puzzles are used in scheduling, planning, and resource allocation problems throughout computer science.
The backtracking search algorithm is the basis of many AI techniques, including the popular DPLL algorithm for SAT solving, which underpins modern automated theorem provers. Constraint propagation, a refinement of backtracking that uses information from the constraints to prune the search space more aggressively, is used in production-quality solvers like Choco and Gecode.
In CTF competitions, cryptarithmetic puzzles occasionally appear as a brain teaser or as one step in a multi-stage puzzle. The standard approach is to use a constraint solver or write a quick backtracking search. Recognizing the puzzle format (an arithmetic equation with letters in place of digits) is the key skill.
The puzzles also have historical significance as a popular form of recreational mathematics in the 19th and early 20th centuries. Lewis Carroll (author of Alice in Wonderland) was a noted cryptarithmetic puzzle composer, and the puzzles were a regular feature in newspapers and puzzle books of the era.
The technique of solving arithmetic constraints with backtracking is also the foundation of program synthesis, where the goal is to find a program that satisfies a given specification. Modern program synthesis tools like Rosette and Sketch use similar backtracking search to explore the space of possible programs and find one that meets the constraints.
In the context of cryptography, cryptarithmetic puzzles are occasionally used as a form of proof-of-work. The Bitcoin blockchain uses a hash-based proof-of-work, but earlier proposals for digital cash (like Hashcash by Adam Back) used similar search problems. The connection is that finding a solution requires computational work, which can be used to limit spam or denial-of-service attacks.
The puzzles are also pedagogically valuable because they teach the fundamental concept of search with backtracking, which is the basis of much of artificial intelligence. Understanding how to set up a search problem, prune the search space, and propagate constraints is essential for any AI practitioner.
Conclusion
In this cryptarithmetic puzzle solver java tutorial we built a complete constraint satisfaction solver using backtracking search, walked through every line of code, and explained the historical context of one of the oldest puzzles in recreational mathematics. You now understand constraint satisfaction, backtracking search, and the connection between puzzles and modern AI techniques. Next, study the statistical attack on substitution ciphers, which combines frequency analysis with hill climbing to break monoalphabetic ciphers that are too complex for simple analysis.
Comments
Comments
Post a Comment