What is the best way to simplify/optimize a piece of code that looks at combinations of conditions?
algorithm, optimization
Solution
Well, the most pleasant way to write that would probably be
if(cond1 + cond2 + cond3 + cond4 == 3)
{
if(!cond1)
{
// do something
}
else if(!cond2)
{
// do something
}
else if(!cond3)
{
// do something
}
else // !cond4
{
// do something
}
}
else
{
// do something
}
I'm wary of those values not being in an array, though.
Problem
I have a piece of code that I want to optimize for readability and performance and coolness. Right now I have this ugly looking thing: ``` if ( cond1 && cond2 && cond3 && !cond4) { // do something } else if ( cond1 && cond2 && !cond3 && cond4) { // do something } else if ( cond1 && !cond2 && cond3 && cond4) { // do something } else if (!cond1 && cond2 && cond3 && cond4) { // do something } else { // do something } ``` where `cond1`, `cond2`, `cond3` and `cond4` are booleans that have been initialized prior to the block of code above. I want to make this faster, less ugly and more cool. I'm thinking about doing this: ``` int val = (cond1 ? 0 : 1) + 2 * (cond2 ? 0 : 1) + 4 * (cond3 ? 0 : 1) + 8 * (cond4 ? 0 : 1); if (val == 8) { // do something } else if (val == 4) { // do something } else if (val == 2) { // do something } else if (val == 1) { // do something } else { // do something } ``` Does that work or are there flaws? Is there a better way? What is the typical way of achieving the desired result when looking through different combinations of multiple conditions?