1

If I have a set of boolean variables in Pascal, how can I test if exactly one of them is True?

Andreas Rejbrand
  • 105,602
  • 8
  • 282
  • 384
vanzuita
  • 37
  • 5
  • 3
    `b1 xor b2 xor b3` is also true if they're ALL true. You should fix the question to say what you really want -- exactly one true or a 3-variable xor. Also, you should say what language you're working in, since they have different syntactical features that might be used. – Matt Timmermans May 15 '21 at 11:27
  • Apparently there is no easy way to do this, I learned this in this post: [link](https://stackoverflow.com/questions/14888174/how-do-i-determine-if-exactly-one-boolean-is-true-without-type-conversion) – vanzuita May 15 '21 at 12:28

1 Answers1

2

In Pascal you can do this:

if Integer(a) + Integer(b) + Integer(c) = Integer(true) then
    writeln("exactly one is true");

It's important to compare to Integer(true), since it could be different values in different versions of Pascal.

Matt Timmermans
  • 53,709
  • 3
  • 46
  • 87
  • I got it. Because the sum can only give Integer 1 to only 1 true. – vanzuita May 15 '21 at 14:13
  • 1
    Please note that in Delphi, a boolean variable *might* (depending on how it was created) be something different from `1 = Ord(True)`. In such strange cases, it is safer to do `Ord(a <> False) + Ord(b <> False) + Ord(c <> False) = 1`. Because even if `a` happens to be `Boolean(4)`, we have `Ord(a <> False) = Ord(True) = 1`. – Andreas Rejbrand May 15 '21 at 19:33