Random Walk Generator
Volume Number: 15 (1999)
Issue Number: 11
Column Tag: Programming Techniques
A Random Walk Generator
by F.C. Kuechmann, Vancouver, WA
A CodeWarrior Pascal implementation of the "random walk" decision simulation technique
Introduction
Humans have seemingly always been fascinated by random phenomena. Randomness is a pervasive component of our everyday lives. It characterizes the patterns of raindrops, shape and location of clouds, traffic on the freeway. It describes the selection of winning numbers in the lottery and day-to-day changes in the weather. The science of chaos says that everything began in pure randomness and will end that way.
The computer provides a means for the systematic extended study of randomness and pseudo-randomness that is impractical using simpler methods such as flipping coins or rolling dice. A graphics-oriented computer and a simple algorithm such as a two-dimensional random walk is ideal for the visual display and exploration of random principles.
The random walk decision procedure, like the eight queens and knight's tour problems, predates computers. In one college finite math textbook (Kemeny et. al. , 1962) it is described in the context of an absorbing (i.e. terminating) Markov chain process wherein, at each decision point, only the most recent decision is considered when making the current one. Variations of the random walk method are currently used with computers to simulate systems in the fields of physics, biology, chemistry, statistics, marketing, population dynamics, and others. A bit of Internet prowling will unearth information on many current applications. An Alta Vista search on the key "random walk" generated 2988 hits, many of them redundant, but containing at least one hit for most of the current applications of the method. Sourcecode for various implementations is freely available on the net in languages ranging from Java to C to Lisp.
Figure 1.A random walk.
The Random Walk Algorithm
In one of its simplest forms, a random walk is an absorbing Markov chain process with three possible outcomes at each step. Each new step can be perpendicular to the previous step (two of the possible outcomes) unless the absorbing state has been reached (the third possible outcome) and no further moves are possible. Absent the absorbing condition, if the previous step moved up or down, the current step must go left or right. If the previous step moved left or right, the current one must move up or down. A somewhat more complex variant adds a fourth possible outcom - continue in the same direction as the previous step. If we go further and allow each step to be in any direction regardless of the previous step, the process generates somewhat more interesting graphic patterns.
An absorbing state is one in which no further steps are possible. For simulation purposes in a college math class we might begin with a jolly drunk at his favorite tavern departing for home. If and when he reaches home, jolly has achieved an absorbing state. Additional absorbing states might be added in the form of policemen, and the tavern itself might be an additional absorbing state - if jolly returns for additional liquid nourishment.
Figure 2.Another random walk.
The Program
Conceptually, implementing a basic random walk is relatively simple. If we assume that each step can be in any of four directions (North-South-East-West, or up-down-left-right) regardless of the direction of the previous step, and that the number of steps is infinite, we can describe the walk in pseudocode as follows
choose starting point
repeat
choose random direction 1-4
step in chosen direction
until forever
If we limit the permissible direction to one perpendicular to the previous direction, for example, things get a bit more complicated because we need to keep track of the direction of each step. One obvious method is with Boolean flag variables. The pseudocode then might look like this
choose starting point
repeat
repeat
choose random direction 1-4
test flags for ok
until direction ok
set and clear flags to track direction
step in chosen direction
until forever
An interactive Mac program gets still more complex. There's little reason to impose undue limits on the possible variations and variables in the walk. We easily can provide for variable fixed or random step lengths, widths, colors and number of steps per walk, as well as variable execution speed. I've allowed for as many variations and possibilities as seem to produce graphically interesting results.
Creating steps
The main part of the program is shown in Listing 1 . After initializing the toolbox, window, menus, global variables, etc, the program executes a loop that repeatedly calls procedures that create new steps, check for events, etc., until the Boolean exit variable ggDoneFlag is TRUE.
Listing 1.
RandomWalk
{Macintosh random walk program in CodeWarrior Pascal}
Program RandomWalk;
uses
Globals,Inits,Misc,StepStuff,GetReady;
{ Main RandomWalk }
begin
Initialize;
GetPen(ggThePoint);
Repeat
NewStep;
CheckEvents;
if ggDoneFlag then
Leave;
{get ready for another round if not quiting}
{and max step count}
if ggStepCount >= ggMaxSteps then
GetReadyForMore
{wait for 'go' button press if single-stepping}
else if ggStepWaitFlag then
begin
ggGoFlag := FALSE;
SetControlTitle(ggGoButtonHdl, 'Go');
CheckEvents;
end
else
Stall(ggStallVal);
Until ggDoneFlag;
end.
The main loop calls the NewStep procedure in Listing 2 for each new step. It first gets a new random 1-10 pixel step width in the variable ggStepWid if the Boolean variable ggRandomWidFlag is TRUE; otherwise the step width value remains that selected via menu. The step width is then saved in the local variable stepWid so that it can be restored if it is reduced later due to proximity to the right or bottom edge of the window. Random step length 1-15 pixels and random color are selected next, if the governing Boolean flags are TRUE. The details of random color selection are discussed later in this article.
NewStep retrieves the saved pen position and calls the procedure GetDirection (Listing 3 ) to select a legal step direction, followed by a call to SetPenAndDeltas (Listing 7 ) to set pen width and height dimensions and the values of variables dX and dY . The pen position must be saved after each step and restored before each new step because clicking the mouse button sets the pen position. If the mouse click is inside the active walking window that point becomes the new pen position; otherwise we test to see if a button on the control panel at right. See the EventStuff source code for details.
For horizontal steps, the horizontal parameter for the toolbox PenSize call is 1, the vertical parameter is that held in the global variable ggStepWid . For vertical steps, the horizontal parameter equals ggStepWid , the vertical 1. The end position co-ordinates after the newly-calculated step are obtained by adding X to dX and Y to dY . We then check to see if the new position is outside the window. If it is, one of the four wrap procedures is called. These procedures draw the step to the edge of the window, then wrap around to the opposite edge of the window if the variable ggWrapFlag is TRUE. If the new endpoint is not outside the window (which is most of the time) the step is drawn in the NewStep procedure by calling the toolbox Line procedure. After a bit of tidying up, the pen location is saved in the global Point variable ggThePoint before exiting.
Listing 2.
NewStep
{ trace a step in the window,}
{ possibly random length, width and color. }
procedure NewStep;
var
dX, dY : integer;
X, Y, newX, newY, dir, stepWid : longint;
begin
Inc(ggStepCount);
UpdateStepCount;
{get new step width if random mode}
if ggRandomWidFlag then
begin
SetRandWid;
UpdateStepWidth;
end;
{save step width}
stepWid := ggStepWid;
{get new step size if random mode}
if ggRandSizeFlag then
begin
SetRandLen;
UpdateStepLen;
end;
{get random step color if random mode}
if ggRandomColorFlag then
SetRandColor
else
SetStepColor;
{save step color}
ggStepColors[ggStepCount] := ggFieldColor;
{fetch pen position}
with ggThePoint do
begin
X := h;
Y := v;
end;
{get random step direction}
GetDirection(dir, X, Y);
SetPenAndDeltas(dir, dX, dY);
MoveTo(X, Y);
{new XY pen co-ordinates after next step}
newX := X + dX;
newY := Y + dY;
{check for wrap-arounds}
if newY < ggMinY then
begin
DoTopWrap(Y, X, dX);
ggWrapDir[ggStepCount] := 1;
end
else if newX > (ggMaxX) then
begin
DoRightWrap(Y, X, dY);
ggWrapDir[ggStepCount] := 2;
end
else if newY > ggMaxY then
begin
DoBottomWrap(Y, X, dX);
ggWrapDir[ggStepCount] := 3;
end
else if newX < ggMinX then
begin
DoLeftWrap(Y, X, dY);
ggWrapDir[ggStepCount] := 4;
end
else
{no boundary problem; draw step here}
Line(dX, dY);
if not ggWrapFlag then
ggWrapDir[ggStepCount] := 0;
GetPen(ggThePoint);
with ggThePoint do
begin
X := h;
Y := v;
end;
MoveTo(X, Y);
GetPen(ggThePoint);
{save pen position for field redraw}
ggStepPositions[ggStepCount] := ggThePoint;
ggStepWid := stepWid;
end;
end.
Selecting direction
There are three button-selectable modes to limit the permissible directions for each new step. A direction is first selected by generating a random integer in the range 1-4. The selected direction is then tested according to the current mode. The work is done in a repeat loop inside the GetDirection procedure shown in Listing 3 .
Listing 3.
GetDirection
{select random direction 1-4, then call move}
{procedures to test legality and distance from}
{right or bottom edge}
procedure GetDirection(var dir, X, Y : longint);
var
count : integer;
randFlag : boolean;
begin
count := 0;
randFlag := FALSE;
repeat
Inc(count);
dir := (abs(Random) mod 4) + 1;
{ test for parallel moves less than 1 stepwidth from }
{ the right or bottom edges. }
case ggWayCount of
ggcPerp:
MovePerp(dir, X, Y, randFlag);
ggcPerpOrFwd:
MovePerpOrFwd(dir, X, Y, randFlag);
ggcAnyWay:
MoveAnyWay(dir, X, Y, randFlag);
end;
until randFlag or (count > 1000);
end;
The integer variable count was used as a safety valve during debugging and could probably be safely deleted. The value of the global integer variable ggWayCount determines which step directions are legal. One of three procedures is selected by the case statement with ggWayCount as the selection index. These procedures, shown in Listing 4a, Listing 4b and Listing 4c use global Boolean flags set by the previous step to determine whether the selected direction is permitted in the current mode. If the step direction is permitted, the called procedure sets the exit variable randFlag to TRUE, sets the global direction flags (either locally or by calling the SetFlags procedure in Listing 5 ) to indicate the new step direction, and then calls the procedures in Listing 6 .
Listing 4a.
MovePerp
{step perpendicular to previous step}
procedure MovePerp(dir : longint; var X, Y : longint;
var randFlag : boolean);
begin
case dir of
ggcUp, ggcDn:
begin
if not ggUpDnFlag then
begin
ggUpDnFlag := TRUE;
ggRtLftFlag := FALSE;
randFlag := TRUE;
CheckRight(X);
end;
end;
ggcRt, ggcLft:
begin
if not ggRtLftFlag then
begin
ggUpDnFlag := FALSE;
ggRtLftFlag := TRUE;
randFlag := TRUE;
CheckBottom(Y);
end;
end;
end;
end;
The default "2-way" mode allows only steps perpendicular to the previous step. The "3-way" mode allows perpendicular and forward steps, and "4-way" mode permits steps in any direction.
Listing 4b.
MovePerpOrFwd
{move any direction but backward}
procedure MovePerpOrFwd(dir : longint; var X, Y : longint;
var randFlag : boolean);
{move any direction but opposite the previous step}
begin
ggUpDnFlag := FALSE;
ggRtLftFlag := TRUE;
{if previous step was up and current step not down}
if ggUpFlag and (dir <> ggcDn) then
begin
SetFlags(dir);
randFlag := TRUE;
case dir of
ggcRt, ggcLft:
CheckBottom(Y);
ggcUp:
CheckRight(X);
end;
end
{if previous step was down and current step not up}
else if ggDnFlag and (dir <> ggcUp) then
begin
SetFlags(dir);
randFlag := TRUE;
case dir of
ggcRt, ggcLft:
CheckBottom(Y);
ggcDn:
CheckRight(X);
end;
end
{previous step to right}
else if ggRtFlag and (dir <> ggcLft) then
begin
SetFlags(dir);
randFlag := TRUE;
case dir of
ggcRt:
CheckBottom(Y);
ggcUp, ggcDn:
CheckRight(X);
end;
end
{previous step to left}
else if ggLftFlag and (dir <> ggcRt) then
begin
randFlag := TRUE;
SetFlags(dir);
case dir of
ggcLft:
CheckBottom(Y);
ggcUp, ggcDn:
CheckRight(X);
end;
end;
end;
Listing 4c.
MoveAnyWay
{step in any direction}
procedure MoveAnyWay(dir : longint; var X, Y : longint;
var randFlag : boolean);
begin
case dir of
ggcUp, ggcDn:
CheckRight(X);
ggcRt, ggcLft:
CheckBottom(Y);
end;
randFlag := TRUE;
end;
Listing 5.
SetFlags
{sets global flags for step direction}
procedure SetFlags(dir : longint);
begin
case dir of
ggcUp :
begin
ggUpFlag := TRUE;
ggDnFlag := FALSE;
ggRtFlag := FALSE;
ggLftFlag := FALSE;
end;
ggcRt :
begin
ggUpFlag := FALSE;
ggDnFlag := FALSE;
ggRtFlag := TRUE;
ggLftFlag := FALSE;
end;
ggcDn :
begin
ggUpFlag := FALSE;
ggDnFlag := TRUE;
ggRtFlag := FALSE;
ggLftFlag := FALSE;
end;
ggcLft :
begin
ggUpFlag := FALSE;
ggDnFlag := FALSE;
ggRtFlag := FALSE;
ggLftFlag := TRUE;
end;
end;
end;
Boundary disputes
The Mac tends to draw an unwanted diagonal line when asked to draw a line parallel to the right or bottom window edge if the line width plus the pen co-ordinate exceeds the maximum permitted - one less than the window border. For example, if the window width is 300, the current X co-ordinate is 295, the horizontal PenSize is 6, and we want to draw a vertical line, we do not get a nice, straight line (and, if we next wrap to the left edge of the window by stepping right, the first line there will be a diagonal). The way I have chosen to handle the problem is to reduce the line width until it no longer exceeds the maximum, or until it reaches the minimum value of 1. In the rare instance that the line width is at the minimum and the sum of the X co-ordinate and width exceeds the permissible maximum, I reduce the X co-ordinate. The window height and Y co-ordinate are handled in a similar manner. The code in Listing 6 , called by the code inListing 4 , performs the edge tests and makes any necessary adjustments.
Listing 6a.
CheckBottom
{checks distance between the Y co-ordinate}
{and bottom of the window; if less than the}
{step width, the step width is reduced; if}
{distance is still too small when step width}
{is 1, the Y co-ordinate is decremented}
procedure CheckBottom(var Y : longint);
var
dif : integer;
begin
{step parallel bottom edge, check distance}
{if too close, make step narrower or move pen}
if (Y + ggStepWid) > ggMaxY then
begin
dif := (Y + ggStepWid) - ggMaxY;
if dif = 0 then
begin
if ggStepWid > 1 then
ggStepWid := ggStepWid - 1
else
Y := Y - 1;
end
else
ggStepWid := ggStepWid - dif;
end;
end;
Listing 6b.
CheckRight
{checks distance between the X co-ordinate}
{and right edge of the window; if less than the}
{step width, the step width is reduced; if}
{distance is still too small when step width}
{is 1, the X co-ordinate is decremented}
procedure CheckRight(var X : longint);
var
dif : integer;
begin
{move is parallel right edge, so check distance}
{if too close, make step narrower if wider than}
{one pixel else move pen left}
if (X + ggStepWid) > ggMaxX then
begin
dif := (X + ggStepWid) - ggMaxX;
if dif = 0 then
begin
if ggStepWid > 1 then
ggStepWid := ggStepWid - 1
else
X := X - 1;
end
else
ggStepWid := ggStepWid - dif;
end;
end;
Listing 7.
SetPenAndDeltas
{using the direction code held in dir, sets pen}
{height and width, saves in global arrays for}
{update, sets vars dX and dY to the distance of}
{the step}
procedure SetPenAndDeltas(dir : longint;
var dX, dY : integer);
begin
case dir of
ggcUp :
begin
PenSize(ggStepWid, 1);
ggStepWidthHor[ggStepCount] := ggStepWid;
ggStepWidthVert[ggStepCount] := 1;
dY := -ggStepSize;
dX := 0;
end;
ggcRt :
begin
PenSize(1, ggStepWid);
ggStepWidthHor[ggStepCount] := 1;
ggStepWidthVert[ggStepCount] := ggStepWid;
dX := ggStepSize;
dY := 0;
end;
ggcDn :
begin
PenSize(ggStepWid, 1);
ggStepWidthHor[ggStepCount] := ggStepWid;
ggStepWidthVert[ggStepCount] := 1;
dY := ggStepSize;
dX := 0;
end;
ggcLft :
begin
PenSize(1, ggStepWid);
ggStepWidthHor[ggStepCount] := 1;
ggStepWidthVert[ggStepCount] := ggStepWid;
dX := -ggStepSize;
dY := 0;
end;
end;
end;
Random colors
Generating random colors that contrast sufficiently with a black background can be a problem. The standard RGB blue, especially, fails to stand out. The following selection method, devised through experimentation, seems to work well.
If the RGB value of either red or green (or both) is negative, contrast is sufficient. Otherwise, ths sum of the values of red, green and blue should exceed 45000. The toolbox Random function returns a signed integer value in the range -32767..32767. In the toolbox, RGBForeColor treats the variables passed to it as red, green and blue values in the color record as unsigned 16-bit integers in the range 0..65535. A "negative" value returned by the Random function is thus treated by RGBForeColor as a value in the range 32768..65535. In Pascal, the requirents can be satisfied by the code in Listing 8 .
Listing 8.
SetRandomColor
{sets a random color for each step, avoiding
insufficient contrast with the background}
procedure SetRandomColor;
var
t: longint;
begin
with ggFieldColor do
begin
repeat
red := Random;
green := Random;
blue := Random;
if (red < 0) or (green < 0) then
Leave;
t := red + green + blue;
until t > 45000;
end;
RGBForeColor(ggFieldColor);
end;
To bound or not to bound
One of the more obvious of the decisions that need to be made in creating a graphical random walk program is what to do when a walk threatens to stray beyond the display window borders, as when the step size plus the current co-ordinate exceeds the size of the window in any direction. Three of the more obvious solutions are
- Scroll the window
- Limit movement to the window
- Wrap around to the opposite edge
I chose to allow switching between the second and third options, limiting steps at the edges or wrapping steps to the opposite edge.
The test to determine whether a step exceeds the window borders is performed in the NewStep procedure shown in Listing 1 . If a boundary is exceeded, one of the procedures in Listing 9 from the StepWraps unit is called to draw the step and, if necessary, perform the wrap around.
Listing 9a.
DoRightWrap
{end of new step exceeds the right border, so wrap}
{around to the left edge of the window}
procedure DoRightWrap(Y, X, dY : integer);
var
rX, dif : integer;
begin
rX := ggMaxX - X;
if rX < 2 then
begin
MoveTo(ggMaxX - 2, Y);
rX := 2;
end;
Line(rX, dY);
if ggWrapFlag then
begin
MoveTo(ggMinX, Y);
dif := ggStepSize - rX;
if dif < 1 then
dif := 1;
Line(dif, dY);
end
else
MoveTo(ggMaxX - ggStepWid, Y);
end;
Listing 9b.
DoBottomWrap
{end of new step exceeds the bottom border, so wrap}
{around to the top edge of the window}
procedure DoBottomWrap(Y, X, dX : integer);
var
rY, dif : integer;
begin
rY := ggMaxY - Y;
Line(dX, rY);
if ggWrapFlag then
begin
MoveTo(X, ggMinY);
dif := ggStepSize - rY;
Line(dX, dif);
end
else
MoveTo(X, ggMaxY - ggStepWid);
end;
Listing 9c.
DoLeftWrap
{end of new step exceeds the left border, so wrap}
{around to the right edge of the window}
procedure DoLeftWrap(Y, X, dY : integer);
var
rX, dif : integer;
begin
rX := X - ggMinX;
if rX < 2 then
begin
MoveTo(2, Y);
rX := 2;
end;
Line(-rX, dY);
if ggWrapFlag then
begin
MoveTo(ggMaxX, Y);
dif := abs(ggStepSize - rX);
Line(-dif, dY);
end;
end;
Listing 9d.
DoTopWrap
{end of new step exceeds the top border, so wrap}
{around to the bottom edge of the window}
procedure DoTopWrap(Y, X, dX : integer);
var
rY, dif : integer;
begin
rY := Y - ggMinY;
Line(dX, -rY);
if ggWrapFlag then
begin
MoveTo(X, ggMaxY);
dif := abs(ggStepSize - rY);
Line(dX, -dif);
end;
end;
Some sourcecode conventions
Sourcecode and CodeWarrior Pro, release 2, Pascal projects for both PowerPC and 68k are provided. The use of descriptive names for constants, variables, functions and procedures makes the CodeWarrior Pascal sourcecode largely self-documenting. Constants and variables that are global to the entire program begin with the letters "ggc" (constants) or "gg" (variables), followed by at least one uppercase alpha or numeric character. They are defined in the Globals unit. Constants and variables global to a single unit begin with "gc" or "g", followed by at least one uppercase alpha or numeric character. The MenuStuff unit holds menu routines, EventStuff the event handlers, etc.
Both PPC and 68k aps are also available for download.
Running the Program
The Buttons
To the left in the Random Land window is the black display field, and on the right is the blue control panel. The control panel displays the number of steps, step size, and step width, and has buttons initially labelled NoWrap, Colors, Clear, 3-Way, Go and Quit.
In its default mode RandomWalks wraps to the opposite window edge when a step exceeds the window boundary. Clicking the NoWrap button sets the mode to prevent wrapping and relabels the button Wrap. Each button click toggles between the two modes.
The Colors control button toggles color selection mode between the default mode in which each of the three RGB values is independently randomly determined using the code in Listing 7 and six fixed saturated colors. The default mode gives a seemingly limitless number of colors.
The Clear button clears the field, resets the step counter to zero, and starts the cycle anew.
The default directions mode is "2-way", which restricts each new step to a direction perpendicular to that of the previous step. The button labelled 3-Way, when clicked, sets the step direction mode to allow steps both perpendicular to and in the same direction as the previous step and the button is then re-labelled 4-Way. The 4-Way button, when clicked, sets the direction mode to allow steps in any of the four possible directions and the button is re-labelled 2-Way. Clicking the button again returns to the default "2-way" mode.
The Go button initiates stepping and is re-labelled Pause when clicked.
The Quit button's function should be a tad obvious and is duplicated by selecting Quit from the File menu or typing Command-Q.
The Menus
The menu bar offers the standard Apple, File and Edit menus on the left, followed by menus to select execution Speed, number of Steps, StepSize, StepWidth, step Color and Delay between cycles. Default values are medium speed, 400 steps, five pixel step size, one pixel step width, random colors and five second delay.
The Walk
To begin random walking, click the Go button. The default origin point for stepping is the middle of the black rectangle, but it can be set to another location by clicking there with the mouse.
Enhancements
The program currently makes "pretty pictures" and would not be suitable to use, for instance, to illustrate the movement in two dimensions of gas molecules in a vacuum for an introductory physics class. It could be modified to provide a simplified demonstration of the general principles involved, however. We might begin with a 1-pixel by 1-pixel step size and initialize 1000 molecules by randomly generating co-ordinates while tracking occupied positions with a 2-D Boolean array. Memory use could be greatly reduced at the expense of some arithmetic by using the individual bits in an array of unsigned integers to track occupancy. Movements are generated by indexing through each position in the 300 by 450 grid. If a position is occupied by a molecule we generate a direction in which to move, otherwise the position is ignored. Each move direction is tested to see if the position in that direction is occupied. If it isn't, erase the current molecule and redraw it in the new location; otherwise we have a collision and both molecules rebound one step. We must also test for the window boundaries. We can update the display as each change is made, or we can make changes initially in the tracking arrays only, then update all at once when the entire field has been scanned.
References
- Kemeny, Schleifer, Snell, and Thompson, Finite Mathematics , Prentice-Hall 1962.
F.C. Kuechmann <fk@aone.com> is a programmer, hardware designer and consultant with degrees from the University of Illinois at Chicago and Clark College. He is building a programmers' clock that gives the time in hexadecimal.