SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,kenrick Mock
Chapter:
Flow Of Control
Exercise:
Programming Projects
Question:8 | ISBN:9780132830317 | Edition: 5

Question

In cryptarithmetic puzzles, mathematical equations are written using letters. Each letter can be a digit from 0 to 9, but no two letters can be the same. Here is a sample problem:

SEND + MORE = MONEY

A solution to the puzzle is S = 9, R = 8, O = 0, M = 1, Y = 2, E = 5, N = 6, D = 7. Write a program that finds a solution to the cryptarithmetic puzzle of the following:

TOO + TOO + TOO + TOO = GOOD

VideoNote Solution to Programming Project 3.9 The simplest technique is to use a nested loop for each unique letter (in this case T, O, G, D). The loops would systematically assign the digits from 0 to 9 to each letter. For example, it might first try T = 0, O = 0, G = 0, D = 0, then T = 0, O = 0, G = 0, D = 1, then T = 0, O = 0, G = 0, D = 2, etc., up to T = 9, O = 9, G = 9, D = 9. In the loop body, test that each variable is unique and that the equation is satisfied. Output the values for the letters that satisfy the equation.


TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Program:

// CryptarithmeticPuzzle.java
public class CryptarithmeticPuzzle
{
	public static void main(String[] args)
	{	
		for (int T = 0; T <= 9; T++)
		{
			for (int O = 0; O <= 9; O++)
			{
				for (int G = 0; G <= 9; G++)
				{
					for (int D = 0; D <= 9; D++)
					{
						if (T != O && T != D && T != G && G != O && G != D && D != O)
						{
							int too = (100 * T) + (10 * O) + O;
							int good = (1000 * G) + (100 * O) + (10 * O) + D;
							
							if (4 * too == good)
							{
								System.out.println("TOO + TOO + TOO + TOO = " 
										+ (4 * too));
								System.out.println("GOOD = " + good);
								System.out.println("Therefore, T = " + T 
										+ ", O = " + O + ", G = " + G 
										+ ", and D = " + D);
								System.out.println();
							}
						}
					}

				}

			}

		}
	}
}

Output:

TOO + TOO + TOO + TOO = 664
GOOD = 664
Therefore, T = 1, O = 6, G = 0, and D = 4

TOO + TOO + TOO + TOO = 1996
GOOD = 1996
Therefore, T = 4, O = 9, G = 1, and D = 6

 

0 0

Discussions

Post the discussion to improve the above solution.