#include #include "dice.h" // simluate one-dimensional random walk // Owen Astrachan, 8/13/94 class RandomWalk { public: RandomWalk(int maxSteps); // constructor, parameter = max # steps void First(); // take first step of walk bool IsDone(); // returns true if walk finished, else false void Next(); // take next step of random walk void Display(); // current status of walk displayed int GetPosition(); // returns position (x coord) of frog int GetSteps(); // returns # of steps taken by frog private: void TakeStep(); // simulate one step of walk int myPosition; // current x coordinate int mySteps; // # of steps taken int myMaxSteps; // maximum # of steps allowed Dice myCoin; // 2-sided "die" for simulation }; RandomWalk::RandomWalk(int maxSteps) : myCoin(2) // postcondition: all private data fields initialized { myPosition = 0; mySteps = 0; myMaxSteps = maxSteps; } void RandomWalk::TakeStep() // postcondition: one step of random walk taken { switch (myCoin.Roll()) { case 1: myPosition--; break; case 2: myPosition++; break; } mySteps++; } void RandomWalk::First() // postcondition: first step of random walk taken { myPosition = 0; mySteps = 0; TakeStep(); } bool RandomWalk::IsDone() // postcondition: returns true when random walk is finished // i.e., when # of steps taken == max. # of steps { return mySteps == myMaxSteps; } void RandomWalk::Next() // postcondition: next step in random walk simulated { TakeStep(); } void RandomWalk::Display() // postcondition: current status of walk displayed { cout << "pos = " << myPosition << "\t"; cout << "steps = " << mySteps << endl; } int RandomWalk::GetPosition() // postcondition: returns position of "frog" (x coordinate) { return myPosition; } int RandomWalk::GetSteps() // postcondition: returns number of steps taken by "frog" { return mySteps; } int main() { int numSteps; cout << "enter # of steps: "; cin >> numSteps; RandomWalk frog(numSteps); for(frog.First(); ! frog.IsDone(); frog.Next()) { frog.Display(); } cout << "final position = " << frog.GetPosition() << endl; return 0; }