CodeSignal Interview – isCryptSolution

Problem

cryptarithm is a mathematical puzzle for which the goal is to find the correspondence between letters and digits, such that the given arithmetic equation consisting of letters holds true when the letters are converted to digits.

You have an array of strings crypt, the cryptarithm, and an an array containing the mapping of letters and digits, solution. The array crypt will contain three non-empty strings that follow the structure: [word1, word2, word3], which should be interpreted as the word1 + word2 = word3 cryptarithm.

If crypt, when it is decoded by replacing all of the letters in the cryptarithm with digits using the mapping in solution, becomes a valid arithmetic equation containing no numbers with leading zeroes, the answer is true. If it does not become a valid arithmetic solution, the answer is false.

Note that number 0 doesn’t contain leading zeroes (while for example 00 or 0123 do).

Example

For crypt = ["SEND", "MORE", "MONEY"] and

solution = [['O', '0'],
            ['M', '1'],
            ['Y', '2'],
            ['E', '5'],
            ['N', '6'],
            ['D', '7'],
            ['R', '8'],
            ['S', '9']]

the output should be
solution(crypt, solution) = true.

When you decrypt "SEND""MORE", and "MONEY" using the mapping given in crypt, you get 9567 + 1085 = 10652 which is correct and a valid arithmetic equation.

For crypt = ["TEN", "TWO", "ONE"] and

solution = [['O', '1'],
            ['T', '0'],
            ['W', '9'],
            ['E', '5'],
            ['N', '4']]

the output should be
solution(crypt, solution) = false.

Even though 054 + 091 = 145054 and 091 both contain leading zeroes, meaning that this is not a valid solution.

Solution

Idea

I think that this problem is not difficult to solve although it seems pretty complicated. We just need to decompose it to simple pieces and solve one by one.

  • Replace characters in crypt to number from solution.
  • Check the starting zeroes.
  • Check the equation.

Code

function solution(crypt, solution) {
    for (let i = 0; i < solution.length; i++) {
        for (let ii = 0; ii < crypt.length; ii++) {
            crypt[ii] = crypt[ii].replaceAll(solution[i][0], solution[i][1]);
        }
    }
    
    // test valid number
    // should not start with 0
    for (let i = 0; i < crypt.length; i++) {
        if (/^(?:[1-9][0-9]*|0)$/.test(crypt[i]) === false) {
            return false;
        }
    }
    
    return parseInt(crypt[0]) + parseInt(crypt[1]) === parseInt(crypt[2]);
}
Leave a Reply 0

Your email address will not be published. Required fields are marked *