Asked • 07/13/19

How do I determine if *exactly* one boolean is true, without type conversion?

Given an arbitrary list of booleans, what is the most elegant way of determining that *exactly* one of them is true? The most obvious hack is type conversion: converting them to `0` for `false` and `1` for `true` and then summing them, and returning `sum == 1`. I'd like to know if there is a way to do this *without* converting them to ints, **actually using boolean logic**. *(This seems like it should be trivial, idk, long week)* **Edit:** In case it wasn't obvious, this is more of a code-golf / theoretical question. I'm not fussed about using type conversion / int addition in PROD code, I'm just interested if there is way of doing it without that. **Edit2:** Sorry folks it's a long week and I'm not explaining myself well. Let me try this: In boolean logic, ANDing a collection of booleans is true if all of the booleans are true, ORing the collection is true if least one of them is true. Is there a logical construct that will be true if exactly one boolean is true? XOR is this for a collection of two booleans for example, but any more than that and it falls over.

Patrick B.

You have a list of boolean variables , hopefully in an array; Just write a for loop counting how many are true
Report

07/14/19

1 Expert Answer

By:

Patrick B. answered • 07/14/19

Tutor
4.7 (31)

Math and computer tutor/teacher

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.