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 ((fle && ge && hass >= angGlopsi() || asti()) && (!(seca > 6) && le || !(ci != nunri()))) {
    ...
    ...
    // Pretend there is lots of code here
    ...
    ...
} else {
    isiont();
}

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 (ci != nunri() && (!le || seca > 6) || !asti() && (hass <= angGlopsi() || !ge || !fle)) {
    isiont();
} 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 (!en && pi >= om && od == 6 && irvie() || knaIwra() != 2 && irvie() || athStras() && od == 6 && irvie() || knaIwra() != 2 && irvie()) {
    if (knaIwra() != 2 && irvie()) {
        if (irvie()) {
            return true;
        }
        if (od == 6) {
            return true;
        }
    }
    if (i >= 8) {
        return true;
    }
}
if (!al) {
    return true;
}
return false;

Solution

return !al && (i >= 8 || !en && pi >= om || athStras()) && (od == 6 || knaIwra() != 2) && irvie();

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 (!athStras() && pi <= om && i <= 8 || en && i <= 8 || al) {
    if (knaIwra() == 2 && od != 6) {
        if (!irvie()) {
            return false;
        }
    }
}
return true;

Part 3

Simplify the following messy chain of conditionals:

if (e == true) {
    asle();
}
if (prel > 6 && e != true) {
    iora();
} else if (niss == true && e != true && prel < 6) {
    bilSessco();
}
if (jarn == false && e != true && prel < 6 && niss != true) {
    ensip();
} else if (trii == true && e != true && prel < 6 && niss != true && jarn != false) {
    issCer();
} else if (aur == true && e != true && prel < 6 && niss != true && jarn != false && trii != true) {
    throx();
}
if (wi == fu && e != true && prel < 6 && niss != true && jarn != false && trii != true && aur != true) {
    farne();
}

Solution

{
    if (e) {
        asle();
    }
    if (prel > 6) {
        iora();
    }
    if (niss) {
        bilSessco();
    }
    if (!jarn) {
        ensip();
    }
    if (trii) {
        issCer();
    }
    if (aur) {
        throx();
    }
    if (wi == fu) {
        farne();
    }
}

Things to double-check in your solution:


Related puzzles: