Exercise · Volume 1 · 2.1-8
Exercise 2.1-8
not stated yet in Lean solution written
| Rating | 18 |
|---|---|
| Kind | K6, write a program: write a MIX or MMIX program from the written solution |
| Section | Section 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 . 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 of a word, so NEXT EQU 4:5. The null link is .
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 cards, the loop runs times. The time is units, that is for the three first instructions, for each pass, and for ST2.
Check
I ran the program on piles of cards on a MIX simulator. It stored each time, and the running times (without the final halt) were units, as the formula 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 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.