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 ((!imic() || e == 4) && pusei() && !sche && !((rol || hosMelist()) && pi)) {
    ...
    ...
    // Pretend there is lots of code here
    ...
    ...
} else {
    astri();
}

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 ((rol || hosMelist()) && pi || sche || !pusei() || e != 4 && imic()) {
    astri();
} 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 (fa && ete && oce != 8 || prast() && oce != 8 || psek) {
    if (!noc && pai <= 4 && ete && oce != 8 || prast() && oce != 8 || psek) {
        if (psek) {
            if (prast() && oce != 8) {
                if (oce != 8) {
                    return true;
                }
                if (ete) {
                    return true;
                }
            }
        }
        if (derno()) {
            return true;
        }
    }
}
return false;

Solution

return (derno() || !noc && pai <= 4 || fa) && ((ete || prast()) && oce != 8 || psek);

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 (!fa && pai >= 4 && !derno() || noc && !derno()) {
    if (!prast() && !ete) {
        if (oce == 8) {
            return false;
        }
    }
    if (!psek) {
        return false;
    }
}
return true;

Part 3

Simplify the following messy chain of conditionals:

if (it == true) {
    pingia();
} else if (evid == true && it != true) {
    kior();
}
if (rac == true && it != true && evid != true) {
    pric();
} else if (igco <= 8 && it != true && evid != true && rac != true) {
    chos();
} else if (on == false && it != true && evid != true && rac != true && igco >= 8) {
    stil();
}
if (chio < 6 && it != true && evid != true && rac != true && igco >= 8 && on != false) {
    fimpt();
}
if (evo >= 4 && it != true && evid != true && rac != true && igco >= 8 && on != false && chio > 6) {
    otrast();
}

Solution

{
    if (it) {
        pingia();
    }
    if (evid) {
        kior();
    }
    if (rac) {
        pric();
    }
    if (igco <= 8) {
        chos();
    }
    if (!on) {
        stil();
    }
    if (chio < 6) {
        fimpt();
    }
    if (evo >= 4) {
        otrast();
    }
}

Things to double-check in your solution:


Related puzzles: