This is actually a question based entirely on, "Did I cheat?" and, "Did I do this efficiently?" Since I'm just self-study for learning working my way through another book, and I already solved the question. If you don't believe me, go ahead and throw the code that follows in and try it.
Primarily, based on the instructions of the question (given in the code) and keeping in mind:
My logic used to begin coding (also commented in the code)
How far along the material covers
Would you say I "cheated" by solving too much of the question BEFORE coding, and as the book to this point has only covered if, while, for, do-while, and switch statements, would you consider this GOOD and EFFICIENT code, i.e. the programming isn't far longer than it should/needs to be?
I'm sure there are better ways to do it, but it's important that it's taken in the context of what I'm supposed to know AT THIS MOMENT. There may well be a "code breaker" in the STL that would do this all in a single line for all I know.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
|
#include "stdafx.h"
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
/*
Holy digits Batman! The Riddler is planning his next caper somewhere on
Pennsylvania Avenue. In his usual sporting fashion, he has left the address
in the form of a puzzle. The address on Pennsylvania is a four-digit
number where:
• All four digits are different
• The digit in the thousands place is three times the digit in the tens place
• The number is odd
• The sum of the digits is 27
Write a program that uses a loop (or loops) to find the address where the
Riddler plans to strike.
*/
//My logic
//DIGITS: A B C D
//C max is 3
//B C D min is 7
//If A = 9, C = 3
//If A = 6, C = 2
//If A = 3, C = 1
//Sum A B C D = 27
//D is 7, 9 (odd number)
//B is 6, 7, 8, 9
//A must be 9 and C must be 3, as even if digits could repeat, no combination
//otherwise could equal 27. By same logic, no combination lower than B = 6
//and D = 7 appears to work either.
int main()
{
int A{ 9 }, B{ 6 }, C{ 3 }, D{ 7 };
for (B = 6; B <= 9; ++B)
{
if (A + B + C + D == 27 && A != B && A != C && A != D && B != C &&
B != D && D != C)
{
cout << "ADDRESS: " << A << B << C << D << " Pennsylvania Ave.\n";
}
}
D = 9;
for (B = 6; B <= 9; ++B)
{
if (A + B + C + D == 27 && A != B && A != C && A != D && B != C &&
B != D && D != C)
{
cout << "ADDRESS: " << A << B << C << D << " Pennsylvania Ave.\n";
}
}
return 0;
}
|
As far as I can tell, the logic is sound in my initialization decisions, and I receive an answer that complies (9837). Would you consider this good and/or efficient for a beginner? Is there anything you would recommend? Just trying to learn best practices and efficient design.
Appreciate your time!