views:

1739

answers:

20

I have a set of five boolean values. If more than one of these are true I want to excecute a particular function. What is the most elegant way you can think of that would allow me to check this condition in a single if() statement? Target language is C# but I'm interested in solutions in other languages as well (as long as we're not talking about specific built-in functions).

One interesting option is to store the booleans in a byte, do a right shift and compare with the original byte. Something like if(myByte && (myByte >> 1)) But this would require converting the separate booleans to a byte (via a bitArray?) and that seems a bit (pun intended) clumsy... [edit]Sorry, that should have been if(myByte & (myByte - 1)) [/edit]

Note: This is of course very close to the classical "population count", "sideways addition" or "Hamming weight" programming problem - but not quite the same. I don't need to know how many of the bits are set, only if it is more than one. My hope is that there is a much simpler way to accomplish this.

+14  A: 

I would just cast them to ints and sum.

Unless you're in a super tight inner loop, that has the benefit of being easy to understand.

recursive
didnt see your response. i agree.
Victor
Someone has to add the linq version of this:myBools.Cast<int>().Sum() !
Jennifer
+3  A: 

if you mean more than or equal to one boolean equals to true, you could do it like

if (bool1 || bool2 || bool3 || bool4 || bool5)

If you need more than one (2 and above) booleans equal to true, you can try

int counter = 0;
if (bool1) counter++;
if (bool2) counter++;
if (bool3) counter++;
if (bool4) counter++;
if (bool5) counter++;
if (counter >= 2) //More than 1 boolean is true
faulty
+2  A: 

from the top of my head, a quick approach for this specific example; you could convert the bool to an int (0 or 1). then loop through therm and add them up. if the result >= 2 then you can execute your function.

Victor
A: 

In most languages true is equivalent to a non-zero value while false is zero. I don't have exact syntax for you, but in pseudo code, what about:

if ((bool1 * 1) + (bool2 * 1) + (bool3 * 1) > 2)
{
    //statements here
}
Bork Blatt
Not valid in any language where true is equivalent to any non-zero value. (The example only works if 1 is always used for true.)
RobH
+36  A: 

How about

  if ((bool1? 1:0) + (bool2? 1:0) + (bool3? 1:0) + 
      (bool4? 1:0) + (bool5? 1:0) > 1)
      // do something

or a generalized method would be...

   public bool ExceedsThreshold(int threshold, IEnumerable<bool> bools)
    {
       int trueCnt = 0;
       foreach(bool b in bools)
          if (b && (++trueCnt > threshold)) 
              return true;
       return false;          
    } 

or using LINQ as suggested by other answers:

    public bool ExceedsThreshold(int threshold, IEnumerable<bool> bools)
    { return bools.Count(b => b) > threshold; }

EDIT (to add Joel Coehoorn suggestion: (in .Net 2.x and later)

    public void ExceedsThreshold<T>(int threshold, 
                      Action<T> action, T parameter, 
                      IEnumerable<bool> bools)
    { if (ExceedsThreshold(threshold, bools)) action(parameter); }

or in .Net 3.5 and later:

    public void ExceedsThreshold(int threshold, 
            Action action, IEnumerable<bool> bools)
    { if (ExceedsThreshold(threshold, bools)) action(); }
Charles Bretana
To be really slick, have an override that accepts an action as well.
Joel Coehoorn
Suggestion - break the loop as soon as b > threshold.
Vilx-
+1 ExceedsThreshold, -1 first example. If you think you're being clever, you aren't.
sixlettervariables
@Vix, kewl, thx, will make the change...
Charles Bretana
sixlettervariables, what's wrong with the first example. I think it's simple and get's the job done.
Kevin
@Joel, what do you mean by an "action" ??, a delegate to the method to run if the conditional is true?
Charles Bretana
parms->params. Also, you could alter that function to return early.
mackenir
@mackenir, thx..
Charles Bretana
I'm going to award this "best answer" as this is going in the skin of an aspx page and the first solution is perfect for my needs. The second option is great too, but not quite answering the question.
Ola Tuvesson
LFSR: "more than one" not "one or more"
hop
LFSR, prefer working ugly code to pretty wrong code. Your code ignores the threshold requirement, which was the point of this question.
Rob Kennedy
Charles, the added "while" loop makes the whole function wrong. After incrementing trueCnt, test whether the threshold has been reached, and then break.
Rob Kennedy
@Rob, you're right... if threshold was never reached, the while loop would cause the foreach to run again from beginning... I'll fix it..
Charles Bretana
Replace the 'break' with 'return true', then replace the final return with 'return false'. Saves stating the same condition twice.
Daniel Earwicker
@Earwicker, right... golly, is this what collaborative programming is like ??
Charles Bretana
+1  A: 

Casting to ints and summing should work, but it's a bit ugly and in some languages may not be possible.

How about something like

int count = (bool1? 1:0) + (bool2? 1:0) + (bool3? 1:0) + (bool4? 1:0) + (bool5? 1:0);

Or if you don't care about space, you could just precompute the truth table and use the bools as indices:

if (morethanone[bool1][bool2][bool3][bool4][bool5]) {
 ... do something ...
}
frankodwyer
The first part's good, the second part scares me.
Jason Lepack
yes me too. lol. in some cases precomputing helps performance - though I don't think this is one of them :-)
frankodwyer
+1  A: 

I would do something like this, using the params argument.

        public void YourFunction()
        {
            if(AtLeast2AreTrue(b1, b2, b3, b4, b5))
            {
                // do stuff
            }
        }

        private bool AtLeast2AreTrue(params bool[] values)
        {
            int trueCount = 0;
            for(int index = 0; index < values.Length || trueCount >= 2; index++)
            {
                if(values[index])
                    trueCount++;
            }

            return trueCount > 2;

        }
John Sonmez
you can reduce that if statement to : return trueCount >= 2
frankodwyer
also, I'm not sure this particularly meets the definition of "elegant"
stephenbayer
@frankodwyer Thats true, I changed it. I thought it might be more readable with the true, false, but looking at it again the other is definitely better.
John Sonmez
+1  A: 

Not exactly pretty... but here's another way to do it:

if (
    (a && (b || c || d || e)) ||
    (b && (c || d || e)) ||
    (c && (d || e)) ||
    (d && e)
)
Vilx-
You weren't kidding :D
Jason Lepack
stephenbayer
i flubbed at a few points, but I think the logic is clear
stephenbayer
Nice...I might use this as an interview question... "What does this do?" to measure pure intellect, and "What do you think of it as a solution?" to weed out anyone that liked it.
ChrisA
Hehe. :DBut thanks for the idea! :)
Vilx-
Wow! Talk about brute force and bloody ignorance! :-)
RobH
+6  A: 

I'd write a function to receive any number of boolean values. It would return the number of those values that are true. Check the result for the number of values you need to be positive to do something.

Work harder to make it clear, not clever!

private int CountTrues( params bool[] booleans )
{
    int result = 0;
    foreach ( bool b in booleans )
    {
        if ( b ) result++;
    }

    return result;
}
rp
A: 
if (NumberOfTrue(new List<bool> { bool1, bool2, bool3, bool4 }) >= 2)
{
    // do stuff
}

int NumberOfTrue(IEnumerable<bool> bools)
{
    return bools.Count(b => b);
}
AndreasN
+10  A: 

It's time for the obligatory LINQ answer, which in this case is actually quite neat.

var bools = new[] { true, true, false, false, false };

return bools.Count(b => b == true) > 1;
Garry Shutler
Or just Count(b => b)
Daniel Earwicker
Yeah, that works too, I just find my way a smidge clearer
Garry Shutler
+1  A: 

I have a much much better one now and very short!

bool[] bools = { b1, b2, b3, b4, b5 };
if (bools.Where(x => x).Count() > 1)
{
   //do stuff
}
John Sonmez
A few people already wrote that one, albeit with the predicate passed to Count instead of needing the Where.
Daniel Earwicker
+39  A: 

I was going to write the Linq version, but five or so people beat me to it. But I really like the params approach to avoid having to manually new up an array. So I think the best hybrid is, based on rp's answer with the body replace with the obvious Linqness:

public static int Truth(params bool[] booleans)
{
    return booleans.Count(b => b);
}

Beautifully clear to read, and to use:

if (Truth(m, n, o, p, q) > 2)
Daniel Earwicker
The best answer +1
Bent André Solheim
Ah, if only more thought like us, Bent André.
Daniel Earwicker
wow, +1 for readability
sixlettervariables
+2  A: 

Shorter and uglier than Vilx-s version:

if (((a||b||c)&&(d||e))||((a||d)&&(b||c||e))||(b&&c)) {}
some
Holy crap, that's horrible.
recursive
Yep, its horrible but it works (I have verified all combinations).
some
A: 

if((b1.CompareTo( false ) + b2.CompareTo( false ) + b3.CompareTo( false ) + ...) > 1)

// More than one of them are true

...

else

...

Partha Choudhury
A: 

If you only have five different values, you can easily do the test by packing the bits in to a short or an int and checking to see if it is any of the zero or one bit answers. The only invalid numbers you could get would be..

0x 0000 0000 
0x 0000 0001
0x 0000 0010
0x 0000 0100
0x 0000 1000
0x 0001 0000

This gives you six values to search for, put them in a lookup table and if it's not in there, you have your answer.

This gives you a simple answer.

   public static boolean moreThan1BitSet(int b)
   {
      final short multiBitLookup[] = { 
            1, 1, 1, 0, 1, 0, 0, 0,
            1, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0,
            1, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0
      };
      if(multiBitLookup[b] == 1)
         return false;
      return true;
   }

This doesn't scale well past 8 bits, but you only have five.

A: 

I know you specified a 1-line answer, but if have different lines, as per the answer by Martin York, you can put a comment on each line saying what it represents.

SeaDrive
A: 

You mentioned

One interesting option is to store the booleans in a byte, do a right shift and compare with the original byte. Something like if (myByte && (myByte >> 1))

I don't think that expression will give you the result you want (at least using C semantics, since the expression is not valid C#):

If (myByte == 0x08), then the expression will return true even though there's only one bit set.

If you meant "if (myByte & (myByte >> 1))" then if (myByte == 0x0a) the expression will return false even though there are 2 bits set.

But here are some techniques for counting the number of bits in a word:

Bit Twiddling Hacks - Counting bits

A variation you might consider is to use Kernighan's counting method, but bail out early since you only need to know if there's more than one bit set:

int moreThanOneBitSet( unsigned int v)
{
    unsigned int c; // c accumulates the total bits set in v

    for (c = 0; v && (c <= 1); c++)
    {
      v &= v - 1; // clear the least significant bit set
    }

    return (c > 1);
}

Of course, using a lookup table's not a bad option either.

Michael Burr
+1  A: 

While I like LINQ, there are some holes in it, like this problem.

Doing a count is fine in general, but can become an issue when the items your counting take a while to calculate/retrieve.

The Any() extension method is fine if you just want to check for any, but if you want to check for at least there's no built in function that will do it and be lazy.

In the end, I wrote a function to return true if there are at least a certain number of items in the list.

public static bool AtLeast<T>(this IEnumerable<T> source, int number)
{
    if (source == null)
        throw new ArgumentNullException("source");

    int count = 0;
    using (IEnumerator<T> data = source.GetEnumerator())
        while (count < number && data.MoveNext())
        {
            count++;
        }
    return count == number;
}

To use:

var query = bools.Where(b => b).AtLeast(2);

This has the benefit of not needing to evaluate all the items before returning a result.

[Plug] My project, NExtension contains AtLeast, AtMost and overrides that allow you to mix in the predicate with the AtLeast/Most check. [/Plug]

Cameron MacFarland
A: 

If there were millions instead of just 5 you could avoid Count()and do this instead ...

public static bool MoreThanOne (IEnumerable<bool> booleans)
{
    return booleans.SkipWhile(b => !b).Skip(1).Any(b => b);
}
Hightechrider