0

Assume I have the following booleans:

var a;
var b;
var c;
var d;
var e;

I don't care which specific ones are true, or false, just that at least 2 (or more) are true.

Would, or Can I use a bitmask (or generate one from these vars) to determine this, instead of having to run every permutation like this:

if (a or b) || (a or c) || (a or d) || (a or e) || (b or c) || (b or d) || (b or e) || (c or d) || (c or e) || (d or e)?

(edit: correct example)

if (a and b) || (a and c) || (a and d) || (a and e) || (b and c) || (b and d) || (b and e) || (c and d) || (c and e) || (d and e)?

Ta.

simonw16
  • 960
  • 9
  • 25
  • `permutation like this` - that permutation is true if any single one of those vars are true - so, that's not a good start - I think those `or` should be `&&` ... anyway ... `if ((+!!a +!!b +!!c +!!d +!!e) > 1)` - or if those vars are **guaranteed** to be booleans `if ((a+b+c+d+e) > 1)` – Jaromanda X Oct 02 '18 at 00:15
  • Yea you're right its and instead of or for the bracketed sections. The +!! works yep. I didn't think to convert the boolean to an int. If you write this as an answer I can accept it. Also, is this achievable with masks? Lets say I rephrase to say, how to tell if 2 or more bits are set (without caring which one) – simonw16 Oct 02 '18 at 00:20
  • of course it is – Jaromanda X Oct 02 '18 at 00:26
  • I've added testing bits to the answer now – Jaromanda X Oct 02 '18 at 01:26

1 Answers1

2

Adding booleans in javascript coerces the values to numbers ... false=>0, true=>1

therefore

if ((a + b + c + d + e) > 1) {
    // at least 2 are true
}

if however, a-e are not guaranteed to be boolean, but could be truthy/falsey, first coerce the value to boolean (!!v becomes true or false) and add those together

if ((+!!a + !!b + !!c + !!d + !!e) > 1) {
    // at least 2 are true
}

Further to comment

how to tell if 2 or more bits are set (without caring which one)

if (x & (x - 1)) {
    // at least two bits set in x
}

or if you want a more generic test for n bits set

const testIfNBitsSet = (v, n) => v.toString(2).split('1').length > n;
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
  • Thanks for broadening the answer there! Good to see the bitmask alternative. The test will most likely use a bitmask eventually to save on db columns. Right now we just keep adding columns for each new integration that is "active" hence, "true". – simonw16 Oct 03 '18 at 16:42