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 ((eoun || !ang) && !(priIio() < 8 || !a && e && ad) && !(blosk() == 5)) {
    ...
    ...
    // Pretend there is lots of code here
    ...
    ...
} else {
    desh();
}

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 (blosk() == 5 || priIio() < 8 || !a && e && ad || ang && !eoun) {
    desh();
} 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 (siass() == 7 && lalTucder() && falik() && o || u != 7 && o || od) {
    if (asson() == sedi) {
        return true;
    }
    if (ethhot()) {
        return true;
    }
}
return false;

Solution

return ethhot() && asson() == sedi || siass() == 7 && lalTucder() && ((falik() || u != 7) && o || od);

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 (siass() != 7 && asson() != sedi || !ethhot()) {
    if (!lalTucder() && asson() != sedi || !ethhot()) {
        if (u == 7 && !falik() && asson() != sedi || !ethhot()) {
            if (!ethhot()) {
                if (asson() != sedi) {
                    return false;
                }
            }
            if (!o) {
                return false;
            }
        }
        if (!od) {
            return false;
        }
    }
}
return true;

Part 3

Simplify the following messy chain of conditionals:

if (fe != 9) {
    rufror();
}
if (smi && fe == 9) {
    mungje();
} else if (veng == 6 && fe == 9 && !smi) {
    elnio();
}
if (pa == false && fe == 9 && !smi && veng != 6) {
    tesmo();
}
if (slo > ba && fe == 9 && !smi && veng != 6 && pa != false) {
    nenSewhes();
}
if (ce == true && fe == 9 && !smi && veng != 6 && pa != false && slo < ba) {
    gesron();
} else if (so == true && fe == 9 && !smi && veng != 6 && pa != false && slo < ba && ce != true) {
    estru();
}

Solution

{
    if (fe != 9) {
        rufror();
    }
    if (smi) {
        mungje();
    }
    if (veng == 6) {
        elnio();
    }
    if (!pa) {
        tesmo();
    }
    if (slo > ba) {
        nenSewhes();
    }
    if (ce) {
        gesron();
    }
    if (so) {
        estru();
    }
}

Things to double-check in your solution:


Related puzzles: