In Befunge-93, it can often be advantageous to flatten a loop into a single line, with the loop section of code being executed in both directions.
For example, consider the code below, which outputs the letter a
eight times:
"a"9>1-:#v_@
^\,:\<
This can flatten be flattened into a single line by interspersing the loop sequence with bridge instructions (#
):
"a"9>1#\-#,:#:>#\_@
Try it online!
If you're just looking at the non-whitespace characters, you may get the impression that this is longer than the the original. But once you take into account the linefeed and the additional padding required in the two line version, you actually end up saving four bytes.
In this particular case, the code be compressed even further by noting that that sequence :#:
can simply be replaced with :
.
"a"9>1#\-#,:>#\_@
Try it online!
In fact, any time you have the same instruction repeated on either side of a #
command, you can simplify that to just the one instruction, so this is something you should always be looking out for when flattening a loop.
To understand how this works, it can help to write out the loop sequence twice, once with all the characters following the #
removed (i.e. what happens when executing left to right), and once with the characters preceding the #
removed (i.e. executing right to left).
"a"9>1#\-#,:>#\_@
>1 - :> _ ; executing left to right
> \ ,: \_ ; executing right to left
You can clearly see now how this matches the original two line version of the code.
6
We've had a recent Befunge 93 topic, but I think it'd be better to generalise this topic instead. Would that be okay? (and maybe mark which tips are good for which version/s, in the same way that Python tips say whether or not they're Python 2/Python 3 specific)
– Sp3000 – 2015-05-09T19:15:01.857I'm unsure if this should be changed to Befunge in general, but Befunge 93 is much less ideal for golfing than 98. – Justin – 2013-12-20T07:46:43.167