A simple problem involving invariants and termination condition of an iterative process is solved. A simple property of this iterative process is shown.
This problem appears David Gries's The Science of Programming:
You are given a coffee can that contains beans painted either black or white. Next to the can is a large pile of black beans. You perform the following algorithm:
Let N be the number of beans in the can at the current instant of time.
- If N=1, then stop.
- Randomly draw two beans from the can. Call them B0 and B1.
-
If
color
(B0) ≠color
(B1), then return white bean to the can and throw away the black bean. -
If
color
(B0) =color
(B1), then throw away both beans and place a black bean from the pile into the can. - Go to step 1.
Proving that this terminates is easy. Let Nb be the number of
BLACK
beans in the can at the current instant of time
and let Nw be the number of WHITE
beans in the can
at the current instant of time. Also, let N′ be the number of
beans in the can after either steps 3 or 4. The following is
then true:
-
color
(B0) ≠color
(B1) ⇒
N′=(Nb−1)+Nw=N−1
-
color
(B0) =color
(B1) =WHITE
⇒
N′=(Nb+1)+(Nw−2)=N−1
-
color
(B0) =color
(B1) =BLACK
⇒
N′=(Nb−1)+Nw=N−1
"Saying something" about the last remaining bean in terms of the initial number of black and white beans is more open-ended and slightly harder. Looking at the three statements above shows that the number of white beans in the can is always reduced by two. So if Nw is the number of white beans in the can to begin with and B is the last remaining bean in the can then:
odd
(Nw) ⇒ color
(B) = WHITE
What about the reverse? Does:
even
(Nw) ⇒ color
(B) = BLACK
Since the number of beans is always reduced by one at each step and since the number of white beans is always reduced by two in step 2 above, then an even number of white beans to begin with will eventually result in a can filled with black beans and therefore step 3 of the algorithm will never be performed after that point. The algorithm will terminate with one black bean.
The statements can then be made:
odd
(Nw) ⇔ color
(B) = WHITE
even
(Nw) ⇔ color
(B) = BLACK
No comments:
Post a Comment