CARDIAC › Tips and tricks › Comparisons
Let negative mean "none"
Say you want to add up a stack of cards, and you don't know how many there are.
The usual answer is to put a count on the first card and count it down as you go. That works, but it costs you a cell for the count and four instructions every pass just to take one off it and test it.
cell contents notes
10 030 INP 30 cells 10-21: the first card says how many follow; count it down
11 130 CLA 30
12 700 SUB 00
13 320 TAC 20
14 630 STO 30
15 031 INP 31
16 132 CLA 32
17 231 ADD 31
18 632 STO 32
19 811 JMP 11
20 532 OUT 32
21 900 HRS 00
30 000 how many cards are left
31 000
32 000
Step through the natural way in Cardigan
Instead, end the stack with a -1. You're already loading each card into the accumulator to add it, so spotting the end costs you nothing but the TAC, and -1 can never be mistaken for a real card. Once you start doing this you'll see uses everywhere: -1 for "not found", "off the edge", "no more". Whatever you're testing for, make it the negative case.
cell contents notes
10 030 INP 30 cells 10-17: add up cards until a negative one
11 130 CLA 30
12 316 TAC 16 -1 means no more cards
13 231 ADD 31
14 631 STO 31
15 810 JMP 10
16 531 OUT 31
17 900 HRS 00
30 000
31 000
Step through the CARDIAC way in Cardigan
Both add up 3, 4 and 5 and print 12. The counted version takes 15 cells and runs 33 instructions; the -1 version takes 10 cells and runs 23.
From the tips in
cardiac-code on GitHub. All the tips.