Imagine that you are facing a high wall that stretches infinitely in both directions. There is a door in the wall, but you don’t know how far away is the door or in which direction. It is pitch dark, but you have a very dim lighted candle that will enable you to see the door when you are right next to it.
-
Show an algorithm that enables you to find the door by walking at most steps in the worst case, where is the number of steps that you would have taken if you knew where the door is and walked directly to it (note that your algorithm does not know the value of in advance)
-
What is the constant multiple in the worst-case analysis for your algorithm?
-
Observe that if you knew , you could trivially solve the problem in steps in the worst case (since you do not know the direction of the door); an interesting question (beyond the scope of this problem) is: what the minimum constant that can be achieved by a linear-time algorithm (in the worst case)?
Q1
We have three approaches for this problem.
-
a=1 while not find door: walk left a steps a*=2 walk right a steps a*=2
-
a=1 while not find door: walk left to positoin a a*=2 walk right to positoin a a*=2
-
a=1 while not find door: walk left to positoin a walk right to positoin a a*=2
Q2
Approach 1
First, we calculate some values after iteration.
is the value ofa
after iteration. Sincea
doubles twice after each iteration, .
is the total steps we move after iteration. For each iteration, we move left steps and then move right steps. So that .
is the current position after iteration. We assume that the left side of the starting point is negative, and right side is positive. Similarly to , .
is the furthest checked position checked on the left after iteration. Notice that, we can see the positions next to us using the candle. .
Similarly to , is the furthest checked on the right after iteration. .
Due to the defination of , the position of the door is either or . Therefore, we know that if the door is found in the iteration, it’s either or . We can prove that, in the worse case, the door is to the left of the starting point and , which means . In this case, . The constant multiple is .
Approach 2
Similarly, we calculate some values after iteration.
Similarly, .-
Obviously, , .
Obviously, .- For each iteration, we move left steps and then move right steps. So that .
Therefore, we know that if the door is found in the iteration, it’s either or . We can prove that, in the worse case, the door is to the left of the starting point and , which means . In this case, . The constant multiple is .