Search code examples
c++puzzlecryptarithmetic-puzzle

Cryptarithmetic puzzle


I am trying to solve this cryptarithmetic puzzle TWO + TWO = FOUR and I used a raw brute force, but I can't figure out where I am making mistake. The idea here is that it tries all possible combinations of numbers from 0 to 10 and all numbers that are assigned to characters must be distinct. By definition

a cryptarithmetic puzzle is a mathematical game where the digits of some numbers are represented by letters (or symbols). Each letter represents a unique digit. The goal is to find the digits such that a given mathematical equation is verified: In this case:

   TWO
 + TWO
 ------ 
= FOUR

This code goes through all possible combinations until it finds the solution that satisfies the problem. Constraint for it is given in else if statement. First if statement simply checks if numbers are same, and if they are, it just skips that iteration.

My desired output is to see all correct solutions displayed.

int T, W, O, F, U, R;

for (T = 0; T < 10; T++)
{
    for (W = 0; W < 10; W++)
    {
        for (O = 0; O < 10; O++)
        {
            for (F = 0; F < 10; F++)
            {
                for (U = 0; U < 10; U++)
                {
                    for (R = 0; R < 10; R++)
                    {
                        if ((T == W) || (T == O) || (T == F) || (T == U) || (T == R) || (W == O) || (W == F) || (W == U) || (W == R) || (O == F) || (O == U) || (O == R) || (F == U) || (F == R) || (U == R))
                        {
                            continue;
                        }
                        else if (200 * T + 20 * W + 2 * O == F * 1000 + O * 100 + U * 10 + R * 0) {
                            cout << "T = " << T << endl
                                << "W = " << W << endl
                                << "O = " << O << endl
                                << "F = " << F << endl
                                << "U = " << U << endl
                                << "R = " << R << endl << endl;
                            break;
                        }
                    }
                }
            }
        }
    }
}

I get bunch of results and interestingly enough, only the last result is fine, where it gives:

T = 7
W = 6
O = 5
F = 1
U = 3
R = 0

Solution

  • R * 0 should be R * 1 .

    The answer you got that happened to be correct was the one where R = 0 (because when R is 0, R * 0 is the same as R * 1). I guess you also want to start F from 1 as typically cryptarithms don't allow leading zeros.