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.2.5-11

Exercise 2.2.5-11

not stated yet in Lean solution written

Rating21
KindK5, design an algorithm: give a method for a task, often with a cost bound from the written solution
SectionSection 2.2.5 of Volume 1

The task

Design a method for synchronous simulation in which the variables V[k]V[k] change together at the end of a step, using the tables NEWV[k]\mathrm{NEWV}[k] and LINK[k]\mathrm{LINK}[k], and give an error stop when a variable gets two values in the same step.

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

Remember in a list which variables were changed in the step.

Hint 2

Use LINK[k]=0\mathrm{LINK}[k] = 0 to mean that the variable has not been changed.

Solution

Show the solution

Initially LINK[k]←0\mathrm{LINK}[k] \leftarrow 0 for all kk and HEAD←−1\mathrm{HEAD} \leftarrow -1. Values kk are 1,…,n1, \dots, n.

Assignment of a new value xx to V[k]V[k] during a step. If LINK[k]≠0\mathrm{LINK}[k] \ne 0, then V[k]V[k] already has a new value in this step, so stop with an error. Otherwise set NEWV[k]←x\mathrm{NEWV}[k] \leftarrow x, LINK[k]←HEAD\mathrm{LINK}[k] \leftarrow \mathrm{HEAD} and HEAD←k\mathrm{HEAD} \leftarrow k. The old value of V[k]V[k] stays in V[k]V[k], so the other assignments of the step still see the old value.

End of the step. Set k←HEADk \leftarrow \mathrm{HEAD} and HEAD←−1\mathrm{HEAD} \leftarrow -1. While k≥0k \ge 0: set V[k]←NEWV[k]V[k] \leftarrow \mathrm{NEWV}[k], t←LINK[k]t \leftarrow \mathrm{LINK}[k], LINK[k]←0\mathrm{LINK}[k] \leftarrow 0, k←tk \leftarrow t.

The list through LINK\mathrm{LINK} holds exactly the variables changed in the step. The first assignment sets a link that is not 00, since it is either −1-1 or a variable number, so the test of the second assignment works. The time of a step is proportional to the number of variables that change, and not to nn.

If the variables are scattered in memory, the same method works with a NEWV\mathrm{NEWV} field and a LINK\mathrm{LINK} field in the node of each variable, and with HEAD\mathrm{HEAD} pointing at a node.

Check

I ran this method on 2000 random steps with 8 variables. The result matched a copy of the old values updated by the same assignments, the number of list nodes equalled the number of assigned variables, and all links were 00 after the step.

Remarks

The error for a double assignment is only raised when two different assignments are made. If the same value is given twice, the method still reports it, and one may weaken the test to compare the values.

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.