CS 131 Fall 1998
Lab 6: Conditional Execution & Random Walks
In Lab 5, you experimented with code that generated a random walk. The analogy was that of an inebriated person taking randomly-directed steps, with the resulting path being displayed on the graphics screen. The exercises for this lab also involve a random walk but with some important differences:
- The random walk will only travel along one dimension. Imagine the person stumbling in a narrow alley, which constrains movement to two opposing directions.
- The random walk doesn't use graphics to present and maintain the current position. Instead, the code must keep track of the position (along only one dimension) in a variable, and simply the position after each step.
- Rather than execute a specified number of steps, the random walk will continue until it reaches a specified distance away from the starting point. Imagine the person starting out at the midpoint of the alley. By walking a certain distance from his starting point (in either direction), he can exit the alley. Since the number of steps required to reach the desired distance will vary, the random walk must use a while loop.
Random Alley Walks
The incomplete JavaScript code below is intended to simulate a random alley walk as described above. A function called coinFlip is defined to simulate flipping a coin. The alleyWalk function is then supposed to simulate the walk, moving the walker back and forth along the alley until the specified goal distance is reached. The missing code (which you will write below) determines the direction in which the walker moves, based on a call to the coinFlip function. If the call returns "heads", then the walker will move to the right (i.e., its position will increase by 1). Otherwise, it will move to the left (i.e., its position will decrease by 1).
function coinFlip()
// Given : none
// Returns: either "heads" or "tails" at random
{
return randomItem(["heads", "tails"]);
}
function alleyWalk(goalDist)
// Given : goalDist >= 0
// Results: displays the steps in a random alley walk, where
// the walker moves left or right based on a coin flip.
// The walk ends when reach specified goal distance.
{
var position, numSteps;
position = 0; // initialize walker position
numSteps = 0; // initialize step counter
while (Math.abs(position) < goalDist) {
// insert code that calls coinFlip, then either adds
// or subtracts 1 from the current position
numSteps++; // increment counter
document.write(numSteps + ": " + position + "
");
}
}
EXERCISE 1:
Cut-and-paste the above code into the JavaScript interpreter, and complete the definition of the alleyWalk function by replacing the comment inside the while loop with the appropriate code. Since your code is enclosed inside a while loop, you should be especially careful in proof-reading it before attempting to execute. If your code updates the position variable incorrectly, an infinite loop is possible.
Once you have added the appropriate code and tested it, save a copy of the alleyWalk function in the Lab6 document. Then, make each of the following calls 5 times and report the number of steps required for each walk.
alleyWalk(5)
alleyWalk(10)
alleyWalk(20)
How consistent are the numbers that you obtained for each goal distance? Are the numbers more or less consistent when the goal distance is increased? Try to explain why.
As was the case with the two-dimensional random walk from Lab 5, the expected number of steps required by a one-dimensional random walk is known: on average, it takes roughly D2 steps to reach a goal distance of D from the start position. Do the numbers you obtained support this estimate? Explain.
Since the expected number of steps required by an alley walk is the square of the goal distance, it follows that if you double the goal distance, the expected number of steps goes up by a factor of 4. Do your numbers support this expectation? Explain.
Average Walking Distance
As you probably noticed, there can be large variations in the numbers of steps required for random walks. For example, a sequence of nothing but heads will result in the shortest possible walk, while a sequence of alternating heads and tails will get you nowhere. If you perform only a few simulations, extreme cases such as these may occur and skew your results. By simulating a large number of random walks and averaging the results, however, rare cases such as these have minimal impact on the final average. The average number of steps taken over a large number of random walks should consistently approach the expected value.
Clearly, simulating each random walk separately and averaging the results yourself is not an attractive option when the number of desired simulations is large. Instead, you would like to automate the simulations, using a variable to keep track of the total number of steps taken by the walks, which could then be used to compute the average.
EXERCISE 2:
As is, the alleyWalk function is not amenable to automating the simulations. The problem is that it displays the number of steps taken by a walk on the screen using a write statement. While this allows the user to view this number, it does not allow for other JavaScript code to access it. In contrast, a value returned by a function would be accessible since a function call can be used in an expression or assigned to a variable.
Make the following two modifications to the alleyWalk to allow for automation of the random walk simulations.
- Modify the function so that it returns the final number of steps taken by the walk. As always, you should be careful to update the comments whenever you change the behavior of a function.
- Since the function is now returning the number of steps, the write statement which displays this information is no longer necessary. In fact, its presence will only serve to slow down the simulation by producing prodigious amounts of output. Comment out the write statement so that the location of the walker is no longer displayed during the walk. That is, put a '//' at the beginning of the line so that the write statement will be ignored by the interpreter.
EXERCISE 3:
Once you have modified the alleyWalk function to return the number of steps taken by a walk, you can use the following code to perform numerous simulations and average the number of steps taken.
numWalks = parseFloat( prompt("Enter the number of walks to be " +
"performed (positive integer):", ""));
goalDist = parseFloat( prompt("Enter the goal distance for each " +
"walk (positive integer):", ""));
stepCount = 0;
for (i = 1; i <= numWalks; i++) {
stepCount = stepCount + alleyWalk(goalDist);
}
document.write("(" + numWalks + " walks, goal " + goalDist + ") " +
"average number of steps = " + stepCount/numWalks);
Cut-and-paste this code into the interpreter below the alleyWalk function, and execute it 5 times each for the following values. List your results below:
25 walks, goal distance 1
25 walks, goal distance 5
50 walks, goal distance 5
100 walks, goal distance 5
25 walks, goal distance 10
50 walks, goal distance 10
100 walks, goal distance 10
Does increasing the number of walks increase the consistency of the average? Should it?
Do the results of these experiments support your earlier statements regarding the consistency of the numbers when the goal distance is increased?
Do these result come close to the expected number of steps per walk (goal distance squared)? Correspondingly, does doubling the length of the walk increase the number of expected steps by a factor of 4?
Dead-end Alley
Now consider a variation of the alley walk which takes place in a dead-end alley. The person starts out at the wall, and can only exit at the other end. If he is against the wall and takes a step in that direction, he merely bumps into the wall and stays where he is. At any other place in the alley, however, he is free to move in either direction as before.
EXERCISE 4:
Modify your alleyWalk function to match the above dead-end scenario. That is, the walker should behave exactly as before, except in the case where it is up against the wall (position 0) and flips "tails". In this case, the walker's position should remain unchanged, although this should still count as a step.
In order to test your modified function, you might find it useful to temporarily uncomment the write statement. By doing so, you can trace the movement of the walker and verify that it behaves as desired. Once you have done this, you can comment out the write statement again.
Save a copy of your modified alleyWalk definition in the Lab6 document.
EXERCISE 5:
Using your modified alleyWalk function, perform the same series of experiments as in Exercise 5. That is, execute the averaging code 5 times each for the following values, and list your results below:
25 walks, goal distance 1
25 walks, goal distance 5
50 walks, goal distance 5
100 walks, goal distance 5
25 walks, goal distance 10
50 walks, goal distance 10
100 walks, goal distance 10
How does the open alley walk compare to the dead-end alley walk. Does one take longer than the other? What patterns do you see? Elaborate and explain your answers.
Hand in a printout of the Lab6 document, attached to these sheets.