Switch statements
CJam doesn't have switch statements. Nested if statements work just as well, but {{}{}?}{}?
is already 12 bytes long...
If we can transform the condition into a small, non-negative integer, we can transform all case statements in a delimited string and evaluate the corresponding result.
For example, if we want to execute code0
if the integer of the stack is 0, code1
if it is 1, and code2
if it is 2, we can either use
_{({code2}{code1}?}{;code0}?
or
[{code0}{code1}{code2}]=~
or
"code0 code1 code2"S/=~
S/
splits the string into ["code0" "code1" "code2"]
, =
extracts the corresponding chunk, and ~
evaluates the code.
Click herehere to see switch statements in action.
Finally, as suggested by suggested by @jimmy23013 and @RetoKoradi, we can shorten the switch even more in some cases. Say code0
, code1
and code2
have lengths L0, L1 and L2, respectively.
If L0 = L1 ≥ L2
"code0code1code2"L/=~
can be used instead, where L
is L0. Instead of splitting at a delimiter, /
splits the string into chunks of equal length here.
If L0 ≥ L1 ≥ L2 ≥ L0 - 1,
"cccooodddeee012">3%~
can be used instead. >
removes 0, 1 or 2 elements from the beginning of the string, and 3%
extracts every third element (starting with the first).