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 (ce || cridoc() > sorSwin() || !siph || !kalsa() && iola || thes() || !(ec >= 3)) {
    ...
    ...
    // Pretend there is lots of code here
    ...
    ...
} else {
    dalsin();
}

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 (ec >= 3 && !thes() && (!iola || kalsa()) && siph && cridoc() < sorSwin() && !ce) {
    dalsin();
} 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 (drer != iboss() && sqou || vitlo()) {
    if (u && sqou || vitlo()) {
        if (uswi && awri() && sqou || vitlo() || jesm() && awri() && sqou || vitlo()) {
            if (vitlo()) {
                if (sqou) {
                    return true;
                }
            }
            if (awri()) {
                return true;
            }
            if (prun() == 6) {
                return true;
            }
        }
    }
}
return false;

Solution

return ((prun() == 6 || uswi || jesm()) && awri() || u || drer != iboss()) && (sqou || vitlo());

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 (drer == iboss() && !u && !awri() || !jesm() && !uswi && prun() != 6) {
    if (!sqou) {
        return false;
    }
    if (!vitlo()) {
        return false;
    }
}
return true;

Part 3

Simplify the following messy chain of conditionals:

if (psar) {
    sepo();
} else if (olco == true && !psar) {
    pral();
}
if (os == mu && !psar && olco != true) {
    nirJinco();
}
if (!posm && !psar && olco != true && os != mu) {
    idont();
}
if (to && !psar && olco != true && os != mu && posm) {
    salga();
}
if (pra == true && !psar && olco != true && os != mu && posm && !to) {
    sebres();
}
if (oino == 7 && !psar && olco != true && os != mu && posm && !to && pra != true) {
    miiun();
}

Solution

{
    if (psar) {
        sepo();
    }
    if (olco) {
        pral();
    }
    if (os == mu) {
        nirJinco();
    }
    if (!posm) {
        idont();
    }
    if (to) {
        salga();
    }
    if (pra) {
        sebres();
    }
    if (oino == 7) {
        miiun();
    }
}

Things to double-check in your solution:


Related puzzles: