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 ((ewnFusci() || o == meskil() || iabid()) && iotpre() && !(pe < 3) && elso()) {
    ...
    ...
    // Pretend there is lots of code here
    ...
    ...
} else {
    afra();
}

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 (!elso() || pe < 3 || !iotpre() || !iabid() && o != meskil() && !ewnFusci()) {
    afra();
} 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 (opin() <= siga && ica && scos >= 7 && dulEgra() || sejur() && opar()) {
    if (sejur() && opar()) {
        if (dulEgra()) {
            return true;
        }
        if (scos >= 7) {
            return true;
        }
    }
    if (ica) {
        return true;
    }
    if (cefu()) {
        return true;
    }
}
return false;

Solution

return (cefu() || opin() <= siga) && ica && (scos >= 7 && dulEgra() || sejur() && opar());

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 (!ica || opin() >= siga && !cefu()) {
    if (!sejur() && !dulEgra() || scos <= 7) {
        if (scos <= 7) {
            if (!dulEgra()) {
                return false;
            }
        }
        if (!opar()) {
            return false;
        }
    }
}
return true;

Part 3

Simplify the following messy chain of conditionals:

if (ad <= 4) {
    trie();
} else if (cex == true && ad >= 4) {
    lendid();
} else if (aerb != ang && ad >= 4 && cex != true) {
    trui();
}
if (kad == false && ad >= 4 && cex != true && aerb == ang) {
    gocess();
}
if (he == true && ad >= 4 && cex != true && aerb == ang && kad != false) {
    jeoAhin();
} else if (stol >= 9 && ad >= 4 && cex != true && aerb == ang && kad != false && he != true) {
    touss();
}

Solution

{
    if (ad <= 4) {
        trie();
    }
    if (cex) {
        lendid();
    }
    if (aerb != ang) {
        trui();
    }
    if (!kad) {
        gocess();
    }
    if (he) {
        jeoAhin();
    }
    if (stol >= 9) {
        touss();
    }
}

Things to double-check in your solution:


Related puzzles: