Inverse flag update
Sometimes a challenge asks to determine a data set's specific boolean property. To avoid the unacceptably long return
keyword, I often use a flag variable which gets updated in a loop and assign-returned at the end (I will refer to this tip for more detail on assign-returning).
When working with such boolean flags and boolean values, to update them I often use either f&=a|b
or f*=a|b
to align them with the result of a|b
. This is equivalent to saying f = f && (a|b)
.
However, sometimes a flag needs to be inversely updated, meaning f = f && !(a|b)
. Naively, one would use f&=!(a|b)
(9 bytes), or -- using fundamental logical equivalences -- one would golf it to f&=!a&!b
(8 bytes).
For the case of an inverse flag update, though, one might be better off using the binary shift right operator >>
, as the previous assignment is (when working with boolean values) equivalent to f>>=!(!a&!b)
, which simply golfs to f>>=a|b
(7 bytes).
If the flag update in question does not involve parentheses due to negation (as in the previous example), inverse flag updating may still be shorter, as for example f&=!a|!b
(8 bytes) is equivalent to f&=!(a&b)
(9 bytes), which is equivalent to f>>=a&b
(7 bytes).
Inverse flag updating may in certain cases also be used even though the values in question are not boolean (either 0
or 1
).
If only one operand is boolean, bitwise and (&
) can still be used, as the second operand's bits will all be cleared. When using bitwise or (|
) or both operands are non-boolean, one should consider using logical and (&&
) and logical or (||
) to get a boolean result, even though they are one byte longer.
As a side node, these rules also apply when the expression is side-effect-dependent, meaning !f()&&!g()
is equivalent to !(f()||g())
regarding the execution of g()
, such that even in those cases inverse flag updating can be used.
For testing purposes, I wrote a simple truth table tester (TIO-link).
One recent real-world example of this technique in action would be for example my answer to Detect Rectangular Text.