Shortening IF
statements
IF
statements are rather expensive, and golfing them down can save a lot of bytes.
Consider the following (adapted from an answer by Erik the Outgolfer):
IF RND<.5THEN
x=x-1
a(i)=1
ELSE
y=y-1
a(i)=0
ENDIF
The first thing we can do is save the ENDIF
by using a single-line IF
statement:
IF RND<.5THEN x=x-1:a(i)=1ELSE y=y-1:a(i)=0
This works as long as you don't try to put it on the same line as anything else. In particular, if you have nested IF
statements, only the innermost one can be one-lined.
But in this case, we can eliminate the IF
entirely using math. Consider what we actually want:
- If
RND<.5
is true (-1
), we want:
x
to decrease by 1
y
to stay the same
a(i)
to become 1
- Otherwise, if
RND<.5
is false (0
), we want:
x
to stay the same
y
to decrease by 1
a(i)
to become 0
Now if we save the result of the conditional in a variable (r=RND<.5
), we can calculate the new values of x
, y
, and a(i)
:
- When
r
is -1
, x=x-1
; when r
is 0
, x=x+0
.
- When
r
is -1
, y=y+0
; when r
is 0
, y=y-1
.
- When
r
is -1
, a(i)=1
; when r
is 0
, a(i)=0
.
So our final code looks like:
r=RND<.5
x=x+r
y=y-1-r
a(i)=-r
saving a whopping 20 bytes (40%) over the original version.
The math approach can be applied surprisingly often, but when there's a difference in logic between the two cases (e.g. when you need to input something in one case but not in the other), you will still need to use IF
.