{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

DrunkenWalk

DrunkenWalk - cout.setf(ios:fixed cout.precision(1...

This preview shows pages 1–2. Sign up to view the full content.

#include <iostream> #include <cstdlib> #include <cassert> #include <iomanip> using namespace std; // At position start, move left with bar_chance, otherwise move right // return 1 or length, depending on where the drunk ended up int drunkenWalk(int start, int length, double bar_chance) { int loc = start; do { double p = rand() / static_cast<double>(RAND_MAX); if(p > bar_chance) loc++; else loc--; } while(loc > 1 && loc < length); return loc; } // Repeat the walk a lot, and figure out the result probability double walkProbability(int start, int length, double bar_chance, int repetitions) { int bar_results = 0; for(int i = 0; i < repetitions; i++) { if(drunkenWalk(start,length,bar_chance) == 1) { bar_results++; //cout << "Bar" << endl; } else { //cout << "Home" << endl; } } return static_cast<double>(bar_results) / repetitions; } int main() { srand(time(0)); cout.setf(ios::showpoint);

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: cout.setf(ios::fixed); cout.precision(1); cout << endl; cout << string(20, ' ') << "Bar Home" << endl; cout << string(20, ' ') << "1 |-------------------------| 9" << endl; cout << endl << "If the drunk start at position 's', and moves towards the bar with probability 'p', how often does he end up at the bar?" << endl << endl; // Print the top line of the table. cout << setw(10) << " " << " "; for(int start = 2; start < 9; start++) { cout << setw(10) << start; } cout << endl << string(81, '-') << endl; for(double prob = .1; prob < .99; prob += 0.1) { // Write the left column of the table cout << setw(10) << prob * 100 << "|"; // Compute the actual data for(int start = 2; start < 9; start++) { cout << setw(10) << walkProbability(start, 9, prob, 20000) * 100; } cout << endl; } cout << endl; }...
View Full Document

{[ snackBarMessage ]}

Page1 / 2

DrunkenWalk - cout.setf(ios:fixed cout.precision(1...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online