Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the number of "trues" for n booleans

Boolean a, b, c, d;

I would like to count the number of trues, each result should have its own associated action. Maybe something like:

int result = getResult(a, b, c, d);
switch (result) {
    case 0: break;
    case 1: break;
    case 2: break;
    case 3: break;
    default: break;
}

Any idea of how to write the getResult method body a pretty way? In the example, I used only four, but it should be extendable to a bigger number of booleans. Any other way to proceed is welcome.

like image 771
sp00m Avatar asked Mar 28 '13 10:03

sp00m


2 Answers

Write a variadic method?

int getResult(boolean... vars) {
    int count = 0;
    for (boolean var : vars) {
        count += (var ? 1 : 0);
    }
    return count;
}
like image 151
Oliver Charlesworth Avatar answered Oct 06 '22 23:10

Oliver Charlesworth


A better solution may be to use a BitSet which can be more efficient esp if you have many boolean values.

BitSet bs = new BitSet();
bs.set(1);
bs.set(4);
bs.set(9);
bs.set(16);
int setCount = bs.cardinality(); // 4

Instead of

boolean a, b, c, d;

you have BitSet which can have hundreds or millions of boolean values.

BitSet bs = new BitSet(4);
bs.set(0); // a
bs.set(1); // b
bs.set(2); // c
bs.set(3); // d
int setCount = bs.cardinality(); // 4

When you have a lot of booleans, this solution scales much better. i.e. each boolean uses one bit, however each Boolean is a reference and thus uses 32-bits or up to 32x as much memory. Also cardinality() is implemented for you no matter how many bits/booleans you have.

like image 27
Peter Lawrey Avatar answered Oct 07 '22 00:10

Peter Lawrey