taocp

This site has no text of the book. Keep your own copy of TAOCP next to it. See what is checked.

Exercise · Volume 1 · 2.1-8

Exercise 2.1-8

not stated yet in Lean solution written

Rating18
KindK6, write a program: write a MIX or MMIX program from the written solution
SectionSection 2.1 of Volume 1

The task

Write a MIX program that counts the cards in the pile, as steps B1 to B3 do.

The exact wording is in your copy of the book.

Hints

Open one hint at a time. Try the exercise again after each.

Hint 1

Keep X in an index register, so that the field NEXT(X) is reached by the address 0,1(NEXT).

Hint 2

A J1Z and a J1NZ do the test X=ΛX = \Lambda. Keep N in another register and store it at the end.

Solution

Show the solution

Let rI1 hold X and rI2 hold N. The field NEXT is bytes 4:54{:}5 of a word, so NEXT EQU 4:5. The null link is 00.

NEXT  EQU  4:5
COUNT LD1  TOP        B1. X <- TOP.
      ENT2 0              N <- 0.
      J1Z  DONE       B2. Stop if X = 0.
LOOP  INC2 1          B3. N <- N + 1.
      LD1  0,1(NEXT)      X <- NEXT(X).
      J1NZ LOOP       B2. Repeat if X is not 0.
DONE  ST2  N          Store N.

The first test is the jump J1Z DONE. It is needed, because the pile may be empty, and then the loop body must not run. After this test the loop tests the new value of X at the end, so each pass makes one test only.

For a pile of nn cards, the loop runs nn times. The time is 4n+64n + 6 units, that is 2+1+12 + 1 + 1 for the three first instructions, 1+2+1=41 + 2 + 1 = 4 for each pass, and 22 for ST2.

Check

I ran the program on piles of 0,1,2,3,40, 1, 2, 3, 4 cards on a MIX simulator. It stored N=nN = n each time, and the running times (without the final halt) were 6,10,14,18,226, 10, 14, 18, 22 units, as the formula 4n+64n + 6 says.

Remarks

The loop makes one test per card. A version that tests at the start of each pass needs a second jump and takes 5n+65n + 6 units. Exercise 2.1-9 uses the same walk down the pile and prints each card.

This solution is drafted, and a person has not reviewed it yet. The source.

In Lean

not stated yet The exercise is not stated in Lean yet.

The status is computed from the Lean build. The node of the map.

Something is wrong? Report it.