What you learn today
- Shortest solutions
- Tricks and their cost
- When it goes too far
Code golf is a game among programmers: who solves the task with the fewest lines or characters? For IC10 it is more than fun, because 128 lines and 4096 characters are real limits. Whoever knows the tricks still gets a big script onto one chip.
The most important tricks
| Trick | saves | costs |
|---|---|---|
select instead of a conditional jump | label and jump lines | nothing, often even more readable |
comparison as a number: sgt gives 0 or 1 | whole branches | a little thinking when reading |
clamp instead of max and min | one line | nothing |
| reusing registers | registers | risk of mix-ups |
| raw number instead of define | one line | maintainability |
| leaving out the comment | characters | understanding in three months |
A comparison that keeps calculating as a number replaces a whole branch:
sgt tmp temp GRENZE
mul power tmp 100 # 0 or 100, without a jump
And often the instruction you laboriously rebuild already exists:
max r1 r0 280
min r1 r1 300 # two lines instead of clamp: same result
clamp r1 r0 280 300
When it goes too far
The first three tricks make code shorter and better. The last three only make it shorter. A script with 40 lines that still manages without defines and comments is no masterpiece, but a trap for the next person who has to change it – usually yourself.
That is why the workshop only golfs when a limit really pinches, and then in this order: replace jumps with select, pack repetitions into loops or subroutines, shorten comments. NaN guards and defines stay.
A deleted NaN guard saves one line and in an emergency costs the base. Never cut corners on safety.
Diagram
Exercise
Task
r0 holds a temperature in Kelvin (set by the test). Calculate without a single jump:
r1= 1 below 18 °C, otherwise 0r2= distance to 20 °C as an absolute valuer3= r0 limited to 280 to 300 Kr4=Color.Greenfrom 290 to 296 K inclusive, otherwiseColor.Red
The defines are already there. Can you do it in eight lines below the alias block?
Hints
Hint 1
r1 is a single comparison: slt.
Hint 2
r2: sub, then abs. r3: clamp.
Hint 3
r4: combine sge and sle with and, then select between GRUEN and ROT.
Quiz
3 questions. You pass from 60 % – the server does the grading.
Complete the day
- Passed the simulator exercise
- Passed the quiz with at least 60 %
Without an account progress is saved in this browser only.
Report a mistake in this lesson
Please sign in to report. Sign in