SQ in silver chrome letters, a lab's gear stacked against the S: a rack, two oscilloscopes, pizza boxes and a six-pack. Strange Query Lab

CARDIAC › Tips and tricks › Instructions are numbers

Add 500 to turn an instruction into its partner

Say you want to add up cards with alternating signs: plus, minus, plus, and so on.

You'd probably keep a flag for which way to go next, test it for every card, and flip it each time.

cell  contents  notes
 10      040    INP 40  cells 10-12: add the cards with alternating signs until a negative one
 11      140    CLA 40
 12      326    TAC 26
 13      142    CLA 42  cells 13-21: which way this time? test a flag
 14      319    TAC 19
 15      141    CLA 41
 16      240    ADD 40
 17      641    STO 41
 18      822    JMP 22
 19      141    CLA 41
 20      740    SUB 40
 21      641    STO 41
 22      143    CLA 43  cells 22-27: swap the flag, -1 - sign
 23      742    SUB 42
 24      642    STO 42
 25      810    JMP 10
 26      541    OUT 41
 27      900    HRS 00
 40      000
 41      000
 42      000    0: add, -1: subtract
 43     -001

Step through the natural way in Cardigan

This one is my favorite. CARDIAC's instructions pair up five apart: INP and OUT, CLA and STO, ADD and SUB, TAC and JMP, SFT and HRS. And a cell only keeps three digits, so adding 500 to an instruction turns it into its partner, and adding 500 again turns it back. ADD 51 is 251; add 500 and you get 751, which is SUB 51; add 500 again and you get 1251, which the cell keeps as 251. So the program just adds 500 to its own ADD after every card, and there's nothing to test. The same move turns a conditional jump into an unconditional one, or an INP that reads a card into an OUT that outputs one.

cell  contents  notes
 10      040    INP 40  cells 10-21: add the cards with alternating signs until a negative one
 11      140    CLA 40
 12      320    TAC 20
 13      141    CLA 41
 14      240    ADD 40  becomes SUB, then ADD again
 15      641    STO 41
 16      114    CLA 14
 17      242    ADD 42  add 500 to cell 14
 18      614    STO 14
 19      810    JMP 10
 20      541    OUT 41
 21      900    HRS 00
 40      000
 41      000
 42      500

Step through the CARDIAC way in Cardigan

Both work out 5 - 3 + 4 and print 6. The flag takes 22 cells and runs 43 instructions; adding 500 takes 15 cells and runs 35.

From the tips in cardiac-code on GitHub. All the tips.