Exercise · Volume 1 · 1.1-1
Exercise 1.1-1
not stated yet in Lean solution written
| Rating | 10 |
|---|---|
| Kind | K5, design an algorithm: give a method for a task, often with a cost bound from the written solution |
| Section | Section 1.1 of Volume 1. Companion chapter: Algorithms |
The task
Rotate the values of four variables one place to the left, so that gets the old , gets the old , gets the old and gets the old , with as few replacements as possible.
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
Look at the swap of two variables in Section 1.1. The extra variable keeps one value that the first replacement would destroy.
Hint 2
A rotation of four values follows a cycle. Save the value that is overwritten first, then let each variable take the value of its neighbour in turn.
Hint 3
A lower bound: look at the first replacement and ask where the old value of the variable that it overwrites can still be found.
Solution
Show the solution
Use one helper variable and five replacements: After the first replacement holds the old . The next three replacements copy into , into and into . Each of them reads a variable that no replacement has changed yet, so each reads an old value. The last replacement puts the old , saved in , into . The result is where the index means the original value.
Five replacements are also the least number. A replacement copies one value into one variable, because the values are arbitrary and no operation on them is known. Each of the four variables ends with a value different from its original value, so each needs at least one replacement, which gives at least . Suppose that exactly replacements do the job. Then each of is the target of exactly one replacement, and no helper variable exists. Let be the target of the first replacement. This replacement destroys the old value of , and no other variable holds a copy of it. But the old value of is needed in the final value of the variable before in the cycle, and that variable is not . It is the target of a later replacement, and at that time the old value of is gone. This is a contradiction. So at least replacements are needed, and the sequence above is best.
Check
Start with . After the state is . After it is , then gives , gives and gives . The final state is , which is the left rotation of .
Remarks
The same method rotates variables with replacements. Exercise 1.1-3 also removes useless replacements, but from an algorithm.
This solution is checked, 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.