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 ((!(ja != 1 && (unro || lo)) && (a && ipro != e || icsed() != 4) || nang() == 8) && !be) {
    ...
    ...
    // Pretend there is lots of code here
    ...
    ...
} else {
    fota();
}

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 (be || nang() != 8 && (icsed() == 4 && (ipro == e || !a) || ja != 1 && (unro || lo))) {
    fota();
} 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 (da && unt || sebugh() && omaSqo() <= 3 && unt || !ses && nen && unt || ploGrar() && nen && unt) {
    if (se) {
        return true;
    }
    if (po) {
        return true;
    }
}
return false;

Solution

return po && se || (da || sebugh() && omaSqo() <= 3 || (!ses || ploGrar()) && nen) && unt;

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 (!nen && omaSqo() >= 3 && !da && !se || !po || !sebugh() && !da && !se || !po || !ploGrar() && ses && omaSqo() >= 3 && !da && !se || !po || !sebugh() && !da && !se || !po) {
    if (!po) {
        if (!se) {
            return false;
        }
    }
    if (!unt) {
        return false;
    }
}
return true;

Part 3

Simplify the following messy chain of conditionals:

if (cu == true) {
    saecle();
}
if (mo == true && cu != true) {
    comuss();
}
if (ce == false && cu != true && mo != true) {
    obong();
} else if (cel == false && cu != true && mo != true && ce != false) {
    nissu();
}
if (as == 5 && cu != true && mo != true && ce != false && cel != false) {
    ressal();
} else if (gi == 7 && cu != true && mo != true && ce != false && cel != false && as != 5) {
    plerd();
} else if ((ro == pri) == true && cu != true && mo != true && ce != false && cel != false && as != 5 && gi != 7) {
    vetcen();
}
if (ris && cu != true && mo != true && ce != false && cel != false && as != 5 && gi != 7 && (ro == pri) != true) {
    cinBuiss();
}

Solution

{
    if (cu) {
        saecle();
    }
    if (mo) {
        comuss();
    }
    if (!ce) {
        obong();
    }
    if (!cel) {
        nissu();
    }
    if (as == 5) {
        ressal();
    }
    if (gi == 7) {
        plerd();
    }
    if (ro == pri) {
        vetcen();
    }
    if (ris) {
        cinBuiss();
    }
}

Things to double-check in your solution:


Related puzzles: