0

Similar to what is the fastest algorithm for permutations of three condition? and Fastest way to find correct combination with set of 8 booleans


I have three boolean values (called a, b, and c), each of which has a different action based on which ones are true. There is one little odd situation here; if a is false then c must also be false. There are six possibilities, and this results in a rather long and ugly looking if statement chain. Here's what I came up with:

if (a)
    {
        if (b)
        {
            if (c)
            {
                doAction1(); // a = true, b = true, c = true
            }
            else
            {
                doAction2(); // a = true, b = true, c = false
            }
        }
        else
        {
            if (c)
            {
                doAction3(); // a = true, b = false, c = true
            }
            else
            {
                doAction4(); // a = true, b = false, c = false
            }
        }
    }
    else
    {
        if (b)
        {
            doAction5(); // a = false, b = true, c = false
        }
        else
        {
            doAction6(); // a = true, b = false, c = false
        }
    }

I would prefer if the code was readable and fast, meaning that I would prefer not to use any weird bitwise operations. This isn't a homework assignment, just a simplified version of part of a personal project.

Community
  • 1
  • 1
BitNinja
  • 1,477
  • 1
  • 19
  • 25

2 Answers2

5

You can always write

if (a && b && c)
{
    action1 ();
}
else if (a && b && ! c)
{
    action2 ();
}
else if (a && ! b && c)
{
    action3 ();
}
else if (a && ! b && ! c)
...

Arguably having fewer nesting levels and fewer braces that are just noise makes it more readable. And you don't need the comments anymore.

gnasher729
  • 51,477
  • 5
  • 75
  • 98
  • 2
    it would be interesting to compare the resulting byte code from this version compared to the OP's original. – Alnitak Jul 16 '14 at 21:00
0
if(a && b && c){
    //a b c true
}
else if(!a && b && !c){
    //a false b true c false
}
else if(a && !b && c{
    //a true b false c true
}
//etc
flup
  • 26,937
  • 7
  • 52
  • 74
J-Dizzle
  • 3,176
  • 6
  • 31
  • 49