Booleans and conditionals: Correct Solution


Part 1

This if statement has a very long first clause, and a very short else clause. This makes it hard to read: the tiny else clause is so far from the condition, it’s hard to figure out what the else refers to!

if (!(xochot() && harSpoi() != ien && neng()) && ente() && !(ma < 9) && aisou() && iea) {
    ...
    ...
    // Pretend there is lots of code here
    ...
    ...
} else {
    iocChaph();
}

Improve readability by refactoring this conditional so that its two clauses are swapped: what is now the second clause (the else clause) comes first, and the first clause comes second.

Solution

if (!iea || !aisou() || ma < 9 || !ente() || xochot() && harSpoi() != ien && neng()) {
    iocChaph();
} else {
    ...
    ...
    // Pretend there is lots of code here
    ...
    ...
}

Things to double-check in your solution:


Part 2

Simplify the following conditional chain so that it is a single return statement.

if (sple() || ourde() || cheim() || en == 8 || rifge() || nico != 2 || siac) {
    if (smas()) {
        return true;
    }
}
return false;

Solution

return smas() || sple() || ourde() || cheim() || en == 8 || rifge() || nico != 2 || siac;

Bonus challenge: rewrite the if/else chain above so that instead of consisting of many return true; statements with one return false; at the end, it has many return false; statements with one return true; at the end.

Solution

if (!smas()) {
    return false;
}
if (!sple()) {
    return false;
}
if (!ourde()) {
    return false;
}
if (!cheim()) {
    return false;
}
if (en != 8) {
    return false;
}
if (!rifge()) {
    return false;
}
if (nico == 2) {
    return false;
}
if (!siac) {
    return false;
}
return true;

Part 3

Simplify the following messy chain of conditionals:

if (ecer == true) {
    eida();
} else if (phas == true && ecer != true) {
    prum();
} else if (e == true && ecer != true && phas != true) {
    scriss();
} else if (!od && ecer != true && phas != true && e != true) {
    bosbim();
}
if (!sian && ecer != true && phas != true && e != true && od) {
    meae();
} else if (tre == true && ecer != true && phas != true && e != true && od && sian) {
    ocan();
} else if (ecer != true && phas != true && e != true && od && sian && tre != true) {
    oirIntsuc();
}

Solution

{
    if (ecer) {
        eida();
    }
    if (phas) {
        prum();
    }
    if (e) {
        scriss();
    }
    if (!od) {
        bosbim();
    }
    if (!sian) {
        meae();
    }
    if (tre) {
        ocan();
    }
    oirIntsuc();
}

Things to double-check in your solution:


Related puzzles: