Logic Gate — Algorithms

Write the boolean expression that matches the target truth table: 18 levels of boolean logic, logic gates and De Morgan's laws.

What you learn in this game

Boolean logic works with two values: true and false. Bang Jaya's test rack tries every combination of the switches at once, one post for each: that is a truth table. Your rule runs at every post as the inside of if ( … ), and the lamp lights when the result is true. Beside each lamp the villager who asked has lit a candle where they want light: make your lamps match the candles. Three basic operators: && (AND, true when both are true), || (OR, true when either is true), ! (NOT, flips the value).

Operator precedence: JavaScript runs ! first, then &&, then ||, the way multiplication comes before addition in arithmetic. So !oli && air reads as (!oli) && air. Brackets change the order: !(oli && air) works out oli && air first, then flips it.

XOR (exclusive OR) is true only when two values are different. A staircase lamp with two switches is XOR: flip either switch and the lamp flips. JavaScript has two ways. a !== b gives true or false. a ^ b is bitwise XOR: both sides become whole numbers (true becomes 1, false becomes 0) and the result is a number. 1 is truthy and 0 is falsy, so if (a ^ b) still works.

Implication, "if a then b", is only false when a is true but b is false: the promise is broken. When a is false the promise is never tested, so it counts as kept. JavaScript writes it with ! and ||.

De Morgan's laws: !(a && b) is the same as !a || !b, and !(a || b) is the same as !a && !b. The ! goes into each part, and the operator swaps. This level's rack only has || and !.

Three switches mean 8 posts: 2 × 2 × 2 possibilities. Operator order: ! first, then &&, then ||. So a && b || c && d already reads as (a && b) || (c && d) without brackets. You can still write brackets to make it easier to read.

What the levels ask

  1. Two conditions that must both be true are written with &&.
  2. OR is written ||: one true is enough.
  3. ! flips a value: !true is false, !false is true.
  4. Flip the result of && with !. Remember, ! runs before &&: to flip the whole thing, use brackets.
  5. For two booleans, "different" is written !==. ^ works too, but its result is a number.
  6. Flip the result of || with !, and do not forget the brackets.
  7. "If the pump runs, there must be water" is the same as "the pump is not running, or there is water".
  8. "Same" for two booleans is written ===.
  9. De Morgan's law: flipping "both" is the same as "one of them is not".
  10. Join each pair with &&, then the pairs with ||. You may leave out the brackets: && runs before ||.
  11. Chain XOR: compare two switches first, then compare the result with the third switch.
  12. Careful: t1 === t2 === t3 reads as (t1 === t2) === t3, which compares a true or false result with t3.

And more, 18 levels in all.