#include #include #include using namespace std; #include "prompt.h" #include "tvector.h" #include "randgen.h" #include "dice.h" class Walker; class WalkRecorder { public: WalkRecorder(); void Record(const Walker& walker); void Print(ostream& out) const; private: static int MAX; tvector myRecord; int myBeyondCount; }; class Walker { public: Walker(WalkRecorder* wrec); void Walk(int steps); int Position() const; void ChangeRecorder(WalkRecorder* wrec); private: int myPosition; WalkRecorder * myRecorder; }; int WalkRecorder::MAX = 100; WalkRecorder::WalkRecorder() : myRecord(2*MAX+1,0), myBeyondCount(0) { // record -MAX..MAX, all zero } void WalkRecorder::Record(const Walker& walker) { int pos = walker.Position(); if (fabs(pos) > MAX) { myBeyondCount++; } else { myRecord[pos+MAX]++; } } void WalkRecorder::Print(ostream& out) const { int lowIndex=-1,highIndex=0,k; for(k=0; k < 2*MAX+1; k++) { if (myRecord[k] != 0) { if (lowIndex == -1) lowIndex = k; highIndex = k; } } if (lowIndex == -1) { out << " no steps taken" << endl; return; } for(k=lowIndex; k <= highIndex; k++) { cout << k-MAX << "\t" << myRecord[k] << endl; } cout << endl << "beyond boundaries = " << myBeyondCount << endl; } Walker::Walker(WalkRecorder * wrec) : myPosition(0), myRecorder(wrec) { } void Walker::Walk(int steps) { Dice d(2); int k; for(k=0; k < steps; k++) { if (d.Roll() == 1) { myPosition++; } else { myPosition--; } myRecorder->Record(*this); } } int Walker::Position() const { return myPosition; } void Walker::ChangeRecorder(WalkRecorder* wrec) { myRecorder = wrec; } int main() { WalkRecorder * rec = new WalkRecorder(); WalkRecorder * rec2 = new WalkRecorder(); Walker w1(rec); Walker w2(rec); int steps = PromptRange("how many steps ",1,10000); w1.Walk(steps); w2.Walk(steps); rec->Print(cout); cout << endl << "another walk" << endl << endl; w1.ChangeRecorder(rec2); w2.ChangeRecorder(rec2); w1.Walk(steps); w2.Walk(steps); rec2->Print(cout); return 0; }