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 (pierm() && camac() && bral == 1 && gadpse() && rirbar() && acrac() && ve) {
    ...
    ...
    // Pretend there is lots of code here
    ...
    ...
} else {
    nelAdur();
}

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 (!ve || !acrac() || !rirbar() || !gadpse() || bral != 1 || !camac() || !pierm()) {
    nelAdur();
} 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 (!ar) {
    if (oic == esa && !veo && !diad) {
        if (!diad) {
            return true;
        }
        if (!veo) {
            return true;
        }
        if (hurOhe()) {
            return true;
        }
        if (ba != me) {
            return true;
        }
        if (husi) {
            return true;
        }
        if (!an) {
            return true;
        }
    }
}
return false;

Solution

return (!an && husi && ba != me && hurOhe() || oic == esa) && !veo && !diad || !ar;

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 (oic != esa && !hurOhe() || ba == me || !husi || an) {
    if (veo) {
        if (diad) {
            return false;
        }
    }
}
if (ar) {
    return false;
}
return true;

Part 3

Simplify the following messy chain of conditionals:

if (sce) {
    esoWreum();
} else if (op != el && !sce) {
    mebe();
}
if (cang != 1 && !sce && op == el) {
    gunac();
}
if (!igia && !sce && op == el && cang == 1) {
    jouc();
} else if (edi >= 8 && !sce && op == el && cang == 1 && igia) {
    neseh();
}
if (iwl == true && !sce && op == el && cang == 1 && igia && edi <= 8) {
    hiuGuil();
}
if (oe == true && !sce && op == el && cang == 1 && igia && edi <= 8 && iwl != true) {
    plad();
}

Solution

{
    if (sce) {
        esoWreum();
    }
    if (op != el) {
        mebe();
    }
    if (cang != 1) {
        gunac();
    }
    if (!igia) {
        jouc();
    }
    if (edi >= 8) {
        neseh();
    }
    if (iwl) {
        hiuGuil();
    }
    if (oe) {
        plad();
    }
}

Things to double-check in your solution:


Related puzzles: