Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding booleans (as integer) [duplicate]

Tags:

c#

boolean

I wrote a code in AS3 which allowed me to check if a particular number of things were true...

If (true + false + true + true + false + true + true < 4)
{

}

When i tried rewriting in C#, it tells me i cannot add type bool and bool. Is the best way of doing this to rewrite it like this? Or is there some simpler work around?

If ((true?1:0) + (false?1:0) + (true?1:0) + (true?1:0) + (false?1:0) + (true?1:0) + (true?1:0) < 4)
{

}
like image 339
Joel Avatar asked Sep 07 '12 11:09

Joel


People also ask

Can you add two booleans?

You can combine two boolean values using the and operator, which looks like two ampersands: && . The and operator evaluates to true whenever the two boolean values on either side of it are also true .

Can a boolean be an integer?

To convert boolean to integer, let us first declare a variable of boolean primitive. boolean bool = true; Now, to convert it to integer, let us now take an integer variable and return a value “1” for “true” and “0” for “false”.

Can you add booleans in JS?

Because you can't add booleans, so it converts them to numbers first.

Can you add booleans C++?

Bool data type in C++In C++, the data type bool has been introduced to hold a boolean value, true or false. The values true or false have been added as keywords in the C++ language.


3 Answers

Try using IEnumerable<T>.Count(Func<T,bool>) from System.Linq, with T as bool, on a params method parameter.

public static int CountTrue(params bool[] args) {    return args.Count(t => t); } 

Usage

// The count will be 3 int count = CountTrue(false, true, false, true, true); 

You can also introduce a this extension method:

public static int TrueCount(this bool[] array) {    return array.Count(t => t); } 

Usage

// The count will be 3 int count = new bool[] { false, true, false, true, true }.TrueCount(); 
like image 185
Joel Purra Avatar answered Sep 23 '22 11:09

Joel Purra


You could create an array and use Count:

if ((new []{true, false, true, true, false, true, true}).Count(x=>x) < 4)
{

}

or the Sum method:

if ((new []{true, false, true, true, false, true, true}).Sum(x=>x?1:0) < 4)
{

}
like image 34
sloth Avatar answered Sep 21 '22 11:09

sloth


Here's a more fun example:

if ((BoolCount)true + false + true + true + false + true + true <= 5)
{
    Console.WriteLine("yay");
}

Using this class:

struct BoolCount
{
    private readonly int c;
    private BoolCount(int c) { this.c = c; }

    public static implicit operator BoolCount(bool b)
        { return new BoolCount(Convert.ToInt32(b)); }

    public static implicit operator int(BoolCount me)
        { return me.c; }

    public static BoolCount operator +(BoolCount me, BoolCount other)
        { return new BoolCount(me.c + other.c); }
}
like image 33
porges Avatar answered Sep 22 '22 11:09

porges