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 (!(!(ehaOuass() && daap()) || !(tes < 9)) && !(!id && (poni && teto || giar < o && !(thewn() == piis)))) {
    ...
    ...
    // Pretend there is lots of code here
    ...
    ...
} else {
    idpo();
}

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 (!id && (poni && teto || giar < o && !(thewn() == piis)) || !(ehaOuass() && daap()) || !(tes < 9)) {
    idpo();
} 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 (!e && tism && os && pocSpu() || mawe() && os && pocSpu() || tei > slana() && os && pocSpu()) {
    if (el < 8) {
        return true;
    }
    if (ene) {
        return true;
    }
    if (toaopt()) {
        return true;
    }
}
return false;

Solution

return toaopt() && ene && el < 8 || (!e && tism || mawe() || tei > slana()) && os && pocSpu();

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 (tei < slana() && !mawe() && !tism && el > 8 || !ene || !toaopt() || e && el > 8 || !ene || !toaopt()) {
    if (!os && el > 8 || !ene || !toaopt()) {
        if (!ene || !toaopt()) {
            if (el > 8) {
                return false;
            }
        }
        if (!pocSpu()) {
            return false;
        }
    }
}
return true;

Part 3

Simplify the following messy chain of conditionals:

if (se == lal) {
    ospa();
}
if (ni && se != lal) {
    slara();
} else if (prid > 1 && se != lal && !ni) {
    hazint();
}
if (nel > 0 && se != lal && !ni && prid < 1) {
    sirb();
}
if (de && se != lal && !ni && prid < 1 && nel < 0) {
    iloGlua();
}
if (iack == true && se != lal && !ni && prid < 1 && nel < 0 && !de) {
    tetnir();
}
if (!al && se != lal && !ni && prid < 1 && nel < 0 && !de && iack != true) {
    epiid();
}
if (se != lal && !ni && prid < 1 && nel < 0 && !de && iack != true && al) {
    olaint();
}

Solution

{
    if (se == lal) {
        ospa();
    }
    if (ni) {
        slara();
    }
    if (prid > 1) {
        hazint();
    }
    if (nel > 0) {
        sirb();
    }
    if (de) {
        iloGlua();
    }
    if (iack) {
        tetnir();
    }
    if (!al) {
        epiid();
    }
    olaint();
}

Things to double-check in your solution:


Related puzzles: