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

Classify with comparisons, not division

Say you want to sort a number from 0 to 999 into one of four bands of 250.

The obvious move is to divide by 250. CARDIAC has no divide, though, so that turns into a loop of subtractions with a counter, and the bigger the number, the longer it runs.

cell  contents  notes
 10      040    INP 40  cells 10-20: the band is x / 250, by subtracting 250 until x goes negative
 11      140    CLA 40
 12      741    SUB 41
 13      319    TAC 19
 14      640    STO 40
 15      142    CLA 42
 16      200    ADD 00
 17      642    STO 42
 18      811    JMP 11
 19      542    OUT 42
 20      900    HRS 00
 40      000
 41      250
 42      000

Step through the natural way in Cardigan

Just ask three questions in a row instead: below 250? below 500? below 750? Each is a SUB and a TAC on whatever the last one left in the accumulator.

cell  contents  notes
 10      040    INP 40  cells 10-25: three compares sort x into four bands
 11      140    CLA 40
 12      741    SUB 41  x - 250
 13      320    TAC 20
 14      741    SUB 41  x - 500
 15      322    TAC 22
 16      741    SUB 41  x - 750
 17      324    TAC 24
 18      544    OUT 44
 19      900    HRS 00
 20      542    OUT 42
 21      900    HRS 00
 22      500    OUT 00
 23      900    HRS 00
 24      543    OUT 43
 25      900    HRS 00
 40      000
 41      250
 42      000
 43      002
 44      003

Step through the CARDIAC way in Cardigan

Both put 600 in band 2. This one's a trade: the comparisons take more cells, 21 against 14, because each band needs its own way out. But they run 10 instructions where the division ran 22, and they never get slower.

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