HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppModerate

Testing for "bouncy" numbers

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
bouncynumberstestingfor

Problem

I have a segment of code:

/*functions return 4 if all digits are the same, 5 if digits are decreasing, 6 if digits are increasing, 7 if number's digits are bouncy.*/
        int variable = 0;
        cout << number << endl;
        variable = sameDigitsTest(number);
        if (variable == 0)
            variable = decreasingTest(number);
        if (variable == 0)
            variable = increasingTest(number);
        if (variable == 0)
            variable = bouncyTest(number);
        /*variable will not be zero any more, hence I do not test for the value zero*/
        if (variable == 4 || variable == 5 || variable == 6){
            cout << "The number is not bouncy." << endl; 
            nonBouncyCounter++;
        }
        if (variable == 7){
            cout << "The number is bouncy." << endl;
            bouncyCounter++;
        }


How can I eliminate all of the if statements to make my code more compact? In fact I was thinking of including a function that includes the functions xTest, and then returning that value and then keeping the two if statements at the end.

Solution

The use of magic numbers isn't great. Your xTest functions should really have Boolean return values, which would allow you to remove the local storage of the result and simplify further (relying on operator short-circuiting):

void testNumber(int number) {
    if (sameDigitsTest(number) || decreasingTest(number) || increasingTest(number)) {
        nonBouncyCounter++;
    }
    else if (bouncyTest(number)) {
        bouncyCounter++;
    }
}


(Note that the latter does actually work with the current int return values, but it appears that you've only coded them that way to fit your original implementation; it's unnecessary complexity.)

Code Snippets

void testNumber(int number) {
    if (sameDigitsTest(number) || decreasingTest(number) || increasingTest(number)) {
        nonBouncyCounter++;
    }
    else if (bouncyTest(number)) {
        bouncyCounter++;
    }
}

Context

StackExchange Code Review Q#74768, answer score: 12

Revisions (0)

No revisions yet.