[Daily Coding Problem 250] Cryptarithmetic Puzzle

A cryptarithmetic puzzle is a mathematical game where the digits of some numbers are represented by letters. Each letter represents a unique digit.

For example, a puzzle of the form:

  SEND
+ MORE
--------
 MONEY

may have the solution:

{‘S‘: 9, ‘E‘: 5, ‘N‘: 6, ‘D‘: 7, ‘M‘: 1, ‘O‘, 0, ‘R‘: 8, ‘Y‘: 2}

Given a three-word puzzle like the one above, create an algorithm that finds a solution.

For simplicity, let‘s assume all letters are upper-case English letters. A naive way of solving this would be to check every numerical value from 0 to 9 for each letter that appears in the 3 words. Return the first letter-to-number mapping that works. Assuming it takes O(N) to validate a mapping, where N is the number of digits in the sum, this would take O(N * 10!).

This naive solution will check a lot of invalid mappings. To reduce the search space, we can use backtracking to cut down on the number of possible mappings to check. For backtracking to be effective, we should be able to construct a partial solution, verify if that partial solution is invalid and check if a mapping is complete.

1. First check if word3 has more letters than both word1 and word2. If this is the case, we can safely assign 1 to the most significant letter in word3.

2. Start dfs from the least significant digit and do the following:

  a. at any given column of digit i, if word1[i] is not mapped, assign an unused number.

  b. dfs on word2[i].

  c. at this point, we‘ve already assigned number to both word1[i] and word2[i]. There will be the following cases.

  c1. if word3[i] has a mapping and it satisfies the sum at this column, advance i to the next higher column and update carry if any, then dfs.

  c2. word3[i] has a mapping and it does not satisfy the sum. return false.

  c3. word3[i] does not have a mapping but the right number that satisfy the sum is already taken by another letter, return false.

  c4. word3[i] does not have a mapping and the right number that satisfy the sum is not taken by another letter, assign this number to word3[i], advance i to the next higher column and update carry if any, then dfs.

The terminating case is that i < 0. It means we‘ve checked all columns with a right mapping. return true in this case.

For each dfs recursive call, we need to check if it returns true or false. If true, we just found a correct mapping and the starting dfs will return true. If false and we‘ve assigned a number to a letter, remember to backtrack so the letter is not mapped and the number is marked as unused. Essentially each dfs assigns an unused number to an unmapped letter if needed, then verify if the current column adds up.

Runtime analysis: There are 10 total possible numbers so the runtime is O(10!) in the worst case. The recursion stack is also bounded by a depth of 10 as its depth only increases when we need to assign an unused number to a letter.

public class CryptarithmeticPuzzle {
    private static int[] res = new int[26];
    public static int[] playPuzzle(String word1, String word2, String word3) {
        Arrays.fill(res, -1);
        boolean[] used = new boolean[10];
        if(word3.length() > word1.length() && word3.length() > word2.length()) {
            res[word3.charAt(0) - ‘A‘] = 1;
            used[1] = true;
        }
        dfs(word1, word2, word3, word1.length() - 1, word2.length() - 1, word3.length() - 1, 0, used);
        return res;
    }

    private static boolean dfs(String w1, String w2, String w3, int i1, int i2, int i3, int carry, boolean[] used) {
        if(i3 < 0) {
            if(carry == 0) {
                return true;
            }
            else {
                return false;
            }
        }
        if(i1 >= 0 && res[w1.charAt(i1) - ‘A‘] < 0) {
            for(int d = 0; d <= 9; d++) {
                if(used[d]) {
                    continue;
                }
                res[w1.charAt(i1) - ‘A‘] = d;
                used[d] = true;
                if(dfs(w1, w2, w3, i1, i2, i3, carry, used)) {
                    return true;
                }
                else {
                    res[w1.charAt(i1) - ‘A‘] = -1;
                    used[d] = false;
                }
            }
            return false;
        }
        if(i2 >= 0 && res[w2.charAt(i2) - ‘A‘] < 0) {
            for(int d = 0; d <= 9; d++) {
                if(used[d]) {
                    continue;
                }
                res[w2.charAt(i2) - ‘A‘] = d;
                used[d] = true;
                if(dfs(w1, w2, w3, i1, i2, i3, carry, used)) {
                    return true;
                }
                else {
                    res[w2.charAt(i2) - ‘A‘] = -1;
                    used[d] = false;
                }
            }
            return false;
        }
        int sum = carry;
        sum += i1 >= 0 ? res[w1.charAt(i1) - ‘A‘] : 0;
        sum += i2 >= 0 ? res[w2.charAt(i2) - ‘A‘] : 0;
        if(res[w3.charAt(i3) - ‘A‘] >= 0 && sum % 10 == res[w3.charAt(i3) - ‘A‘]) {
            return dfs(w1, w2, w3, i1 - 1, i2 - 1, i3 - 1, sum / 10, used);
        }
        else if(res[w3.charAt(i3) - ‘A‘] >= 0 || used[sum % 10]) {
            return false;
        }
        used[sum % 10] = true;
        res[w3.charAt(i3) - ‘A‘] = sum % 10;
        if(dfs(w1, w2, w3, i1 - 1, i2 - 1, i3 - 1, sum / 10, used)) {
            return true;
        }
        used[sum % 10] = false;
        res[w3.charAt(i3) - ‘A‘] = -1;
        return false;
    }

    public static void main(String[] args) {
        int[] res = playPuzzle("SEND", "MORE", "MONEY");
        System.out.println(Arrays.toString(res));
    }
}

原文地址:https://www.cnblogs.com/lz87/p/11306841.html

时间: 2024-10-09 09:59:58

[Daily Coding Problem 250] Cryptarithmetic Puzzle的相关文章

[Daily Coding Problem] 1 (LeetCode 1). Find if two numbers in an array add up to k

This problem was recently asked by Google. Given a list of numbers and a number k, return whether any two numbers from the list add up to k. For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17. Bonus: Can you do this in one

[Daily Coding Problem 68] Count Pairs of attacking bishop pairs

This problem was asked by Google. On our special chessboard, two bishops attack each other if they share the same diagonal. This includes bishops that have another bishop located between them, i.e. bishops can attack through pieces. You are given N b

[Daily Coding Problem 70] Nth perfect number

This problem was asked by Microsoft. A number is considered perfect if its digits sum up to exactly 10. Given a positive integer n, return the n-th perfect number. For example, given 1, you should return 19. Given 2, you should return 28. This is one

Daily Coding Problem: Problem #315

/** * This problem was asked by Google. In linear algebra, a Toeplitz matrix is one in which the elements on any given diagonal from top left to bottom right are identical. Here is an example: 1 2 3 4 8 5 1 2 3 4 4 5 1 2 3 7 4 5 1 2 Write a program t

[Daily Coding Problem 223] O(1) space in order traversal of a binary tree

Typically, an implementation of in-order traversal of a binary tree has O(h) space complexity, where h is the height of the tree. Write a program to compute the in-order traversal of a binary tree using O(1) space. In-order traversal without recursio

Daily Coding Problem: Problem #339

/** * This problem was asked by Microsoft. Given an array of numbers and a number k, determine if there are three entries in the array which add up to the specified number k. For example, given [20, 303, 3, 4, 25] and k = 49, return true as 20 + 4 +

[Daily Coding Problem 290] Quxes Transformation

On a mysterious island there are creatures known as Quxes which come in three colors: red, green, and blue. One power of the Qux is that if two of them are standing next to each other, they can transform into a single creature of the third color. Giv

[Daily Coding Problem 294] Shortest round route with rising then falling elevations

A competitive runner would like to create a route that starts and ends at his house, with the condition that the route goes entirely uphill at first, and then entirely downhill. Given a dictionary of places of the form {location: elevation}, and a di

[Daily Coding Problem] Find the total number of solutions of a linear equation of n variables

Given a linear equation of n variables, find the total number of non-negative integer solutions of it. All coefficients are positive. Example: input: x + 2 * y = 5 output: 3,  the 3 possible integer solutions are x = 1, y = 2; x = 3, y = 1; x = 5, y