in reply to Re: One out of three ain't bad
in thread One out of three ain't bad

Just a comment on forms for this kind of problem.

The first two forms explicitly list each variable only once:

my $only_one = 1 == ($x ? 1 : 0) + ($y ? 1 : 0) + ($z ? 1 :0); + my $only_one = 2 == (! $x) + (! $y) + (! $z);
The second two forms require each variable to be listed twice:
my $only_one = ($x || $y || $z) && (! ($x && $y)) && (! ($y && $z)) && + (! ($z && $x)); my $only_one = (! ($x && $y && $z)) && ($x ^ $y ^ $z);
Just based on this criterion, I'd avoid the 2nd pair of solutions. (Looking at other replies, those with sub, map, grep, or List:Utils will take a list -- easier to maintain.)

-QM
--
Quantum Mechanics: The dreams stuff is made of

Replies are listed 'Best First'.
Re^3: One out of three ain't bad
by Anonymous Monk on Oct 23, 2005 at 23:54 UTC
    I'll disagree here an say a form like...
    if( !$x && !$y && $z or !$x && $y && !$z or $x && !$y && !$z ) { print "Exactly one..."; }
    ...is easier to maintain because it is more explicit as to what is required for a truth value. Anyone versed in boolean algebra will easily recognize the sum-of-product form here and instantly grasp the intent.
      if( !$x && !$y && $z or !$x && $y && !$z or $x && !$y && !$z ) { print "Exactly one..."; }
      I don't think I was clear. I should have added: "How do you expand that for 7, 42, or 105 variables?" It can be done mechanically, fairly easily, but I wouldn't want to end up with an arrangement of 105 x 105, nor would I want to maintain it.

      One might argue that getting from K to K+1 or K-1 variables is also easy (and it is). But I still wouldn't want to deal with it when I could use a list syntax instead.

      Cheers,

      -QM
      --
      Quantum Mechanics: The dreams stuff is made of