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 › Comparisons

Equality is the expensive test

Say you're counting up and want to stop at 7.

The obvious loop keeps going while the count isn't 7. But on CARDIAC "isn't 7" is really two questions: is it below 7, and is it above? Each one is a subtraction and a TAC.

cell  contents  notes
 10      530    OUT 30  cells 10-19: print the count, count one more, go round while it isn't 7
 11      130    CLA 30
 12      200    ADD 00
 13      630    STO 30
 14      731    SUB 31  i - 7: below?
 15      310    TAC 10
 16      131    CLA 31  7 - i: above?
 17      730    SUB 30
 18      310    TAC 10
 19      900    HRS 00
 30      000    the count
 31      007

Step through the natural way in Cardigan

Think about what you actually know. A count that goes up one at a time can't skip past 7, so the moment it stops being below 7, it is 7. Ask only "below 7?" and you're done. When you really do need equality, ask the likely half first. Here the count is below 7 on every pass but the last, which is why the first version's second question only ever runs once.

cell  contents  notes
 10      530    OUT 30  cells 10-16: the same loop, asking only whether the count is below 7
 11      130    CLA 30
 12      200    ADD 00
 13      630    STO 30
 14      731    SUB 31
 15      310    TAC 10
 16      900    HRS 00
 30      000    the count
 31      007

Step through the CARDIAC way in Cardigan

Both print 0 through 6. The equality version takes 12 cells and runs 46 instructions; the below-7 version takes 9 cells and runs 43. In a loop where both halves ran every time, you'd be saving three instructions a pass.

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