Earlz
Earlz

Reputation: 63895

Turn this if-then logic into a boolean expression?

I'm having a bit of a brain fart on making this code more concise(preferably a single boolean expression)

This is my code:

                    if (d.Unemployed)
                    {
                        if (type.Unemployed)
                        {
                            tmp.Unemployed = true;
                        }
                        else
                        {
                            tmp.Unemployed = false;
                        }
                    }
                    else
                    {
                        if (type.Unemployed)
                        {
                            tmp.Unemployed = false;
                        }
                        else
                        {
                            tmp.Unemployed = true;
                        }
                    }

Basically the point is that if either type or d is not unemployed, then tmp should be set to not unemployed.

Upvotes: 4

Views: 3311

Answers (5)

Nick Dandoulakis
Nick Dandoulakis

Reputation: 43140

If we construct a truth table by following the code, we get

d  | type | tmp
---+------+----
1  |   1  |  1
---+------+----
1  |   0  |  0
----+-----+----
0  |   1  |  0
----+-----+----
0  |   0  |  1

The above is equivalent with the negation of the xor operation.

tmp = not (d xor type)

If the language doesn't have the xor operator we can use the != on boolean values.

tmp = ! (d != type);
// or
tmp = d == type;

Upvotes: 9

Shaz
Shaz

Reputation: 15877

tmp.Unemployed = d.Unemployed || type.Unemployed ? !tmp.Unemployed : null;

Upvotes: 0

Paul.s
Paul.s

Reputation: 38728

Thinking about how much "brain fart" this caused you I would consider using a well named variable to avoid having to go through this mental process again in future. Something like this:

isTmpUnemployed = (type.Unemployed == d.Unemployed);
tmp.Unemployed = isTmpUnemployed;

Upvotes: 2

Peter O.
Peter O.

Reputation: 32898

The above code means "both unemployed or both not unemployed". Thus, not (A xor B):

 tmp.Unemployed = ! ( D.Unemployed ^ type.Unemployed)

Upvotes: 0

MRAB
MRAB

Reputation: 20664

How about:

tmp.Unemployed = type.Unemployed == d.Unemployed;

Upvotes: 15

Related Questions