40 likes | 171 Views
frogwalk.cpp. #include <iostream> using namespace std; #include "dice.h" #include "prompt.h" int main() { int numSteps = PromptRange("enter # of steps",0,20000); int position = 0; // starts at position 0 Dice die(2); // used for "coin flipping" int k;
E N D
frogwalk.cpp #include <iostream> using namespace std; #include "dice.h" #include "prompt.h" int main() { int numSteps = PromptRange("enter # of steps",0,20000); int position = 0; // starts at position 0 Dice die(2); // used for "coin flipping" int k; for(k=0; k < numSteps; k++) { switch (die.Roll()) { case1: position++; // step to the right break; case2: position--; // step to the left break; } } cout << "final position = " << position << endl; return 0; }
walk.h class RandomWalk { public: RandomWalk(int maxSteps); // constructor void Init(); // take first step of walk bool HasMore(); // false if walk finished void Next(); // take next step void Simulate(); // take all steps in simulation int Position() const; // returns position (x) int Current() const; // same as position int TotalSteps() const; // total # of steps taken private: void TakeStep(); // simulate one step of walk int myPosition; // current x coordinate int mySteps; // # of steps taken int myMaxSteps; // maximum # of steps allowed };
one frog .... #include "prompt.h" #include "walk.h" int main() { int numSteps = PromptRange("enter # steps",0,30000); RandomWalk frog(numSteps); // a frog frog.Simulate(); cout << "frog position = " << frog.Position() << endl; return 0; } Note:In the textbook p. 316, frog.GetPosition()should be frog.Position()
frogwalk2.cpp .... #include "prompt.h" #include "walk.h" int main() { int numSteps = PromptRange("enter # steps",0,30000); RandomWalk frog(numSteps); // a frog RandomWalk toad(numSteps); // a toad int samePadCount = 0; // # times at same p frog.Init(); // initialize both walks toad.Init(); while (frog.HasMore() && toad.HasMore()) { if (frog.Current() == toad.Current()) { samePadCount++; } frog.Next(); toad.Next(); } cout << "frog position = " << frog.Position() << endl; cout << "toad position = " << frog.Position() << endl; cout << "# times at same location = " << samePadCount << endl; return 0; }