1 / 4

frogwalk.cpp

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;

roz
Download Presentation

frogwalk.cpp

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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; }

  2. 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 };

  3. 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()

  4. 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; }

More Related