So I have the situation where I have one boolean value a and, if that one is true and b<c I want it to end up as true, if a is false and b>c I want it to resolve as true as well. If b=c I want it to be always false, no matter the value b and c are both numbers. My best approach so far is a?b<c:b>c or maybe b^c^a^b<c. Is there any shorter approach? I can’t stop thinking about it, and want confirmation this is the shortest possible way or find the solution...
2 Answers
Yes, it can be shorter!
c-b<a^a beats a?b<c:b>c by 2 bytes. My tests show that it works for any integer, including negatives. The downside to this formula is that a is repeated twice, which may be unideal depending on your situation.
-
2\$\begingroup\$ Very clever. This works for integers because 1) if
ais false,c-b<a^ais true <=>c-b<ais true <=>b>c; 2) ifais true,c-b<a^ais true <=>c-b<ais false <=>c-b<1is false <=>c-b>=1is true <=>b<c. But it sometimes fails for non-integers. \$\endgroup\$Bubbler– Bubbler2022-06-24 06:39:54 +00:00Commented Jun 24, 2022 at 6:39 -
\$\begingroup\$ I think
c<b+a^aalso works, again for integers. \$\endgroup\$Neil– Neil2022-06-24 07:34:15 +00:00Commented Jun 24, 2022 at 7:34 -
\$\begingroup\$ What is precedence order for
c-b<a^a? Is it((c - b) < a) ^ a? \$\endgroup\$Eric Duminil– Eric Duminil2022-06-26 16:04:11 +00:00Commented Jun 26, 2022 at 16:04 -
1\$\begingroup\$ @EricDuminil Yes, you are correct \$\endgroup\$dingledooper– dingledooper2022-07-02 17:59:56 +00:00Commented Jul 2, 2022 at 17:59
I don't think it can be any shorter, at least in the most general case
See dingledooper's 7-bytes solution that works for integers.
If the target expression were a?b<c:b>=c (note the change on the second comparison), the two conditions are exactly the opposite, and we can get away with comparing b and c only once with a^b>=c or !a^b<c.
But, the target is a?b<c:b>c, and since b<c and b>c cannot be inferred from each other, you either need to
- mention
bandctwice each, to carry out two separate comparisons, or - somehow use the three states (negative, zero, positive) of
b-c.
For the first method, you already have the optimal answer. For the second, the best I can get is (c-b)*(a-.5)>0, 14 bytes (TIO).
Also note that b^c^a^b<c doesn't quite work.
-
1\$\begingroup\$ Javascript numbers are floating point, so have 4 states (negative, zero, positive, NaN). Similarly, the relation between a pair of numbers can be above, below, equal, or unordered (one or both NaN). It can still be interesting to golf the case of finite numbers, though, so you can exclude NaN inputs, and the case of
inf-infgivingNaN. \$\endgroup\$Peter Cordes– Peter Cordes2022-06-24 18:19:13 +00:00Commented Jun 24, 2022 at 18:19
aistrue, does it matter what is output ifb>c? same question forabeingfalseandb<c\$\endgroup\$bandcguaranteed to be integers? \$\endgroup\$