rndm_me
rndm_me

Reputation: 29

Shorten multiple ANDs + ORs in one if-statement (+ XOR, regex)

I program a robot in Java and I want it to analyse something if a rock exists and if there's a hill on the right or on the left as well. I have already tried:

if (rockExisting() && hillExisting("left") || rockExisting() && hillExisting("right"))

It's working, but can I shorten it? (E.G. with redex, a friend told me but the Java Reference defeats me.) And can I also use a logical XOR? (like if there's a hill on the right and left, the condition would be false? ("^" doesn't work for me)

Upvotes: 1

Views: 442

Answers (2)

edi
edi

Reputation: 937

With boolean algebra you can simplify the if term/conditions. You could write:

if (rockExisting() && (hillExisting("left") || hillExisting("right")))

according to the distributive law

(a∧b)∨(a∧c) = a∧(b∨c)

  • ... &&
  • ... ||
  • a ... rockExisting()
  • b ... hillExisting("left")
  • c ... hillExisting("right")

Upvotes: 1

davidxxx
davidxxx

Reputation: 131316

if (rockExisting() && hillExisting("left") || rockExisting() && hillExisting("right"))

is the same thing as

if (rockExisting() && (hillExisting("left") || hillExisting("right")))

as && has higher precedence than ||

Upvotes: 5

Related Questions