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

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

View Full Document Right Arrow Icon
#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 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);
Background image of page 1

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

View Full DocumentRight Arrow Icon
Background image of page 2
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 &lt;&lt; endl; cout &lt;&lt; string(20, ' ') &lt;&lt; &quot;Bar Home&quot; &lt;&lt; endl; cout &lt;&lt; string(20, ' ') &lt;&lt; &quot;1 |-------------------------| 9&quot; &lt;&lt; endl; cout &lt;&lt; endl &lt;&lt; &quot;If the drunk start at position 's', and moves towards the bar with probability 'p', how often does he end up at the bar?&quot; &lt;&lt; endl &lt;&lt; endl; // Print the top line of the table. cout &lt;&lt; setw(10) &lt;&lt; &quot; &quot; &lt;&lt; &quot; &quot;; for(int start = 2; start &lt; 9; start++) { cout &lt;&lt; setw(10) &lt;&lt; start; } cout &lt;&lt; endl &lt;&lt; string(81, '-') &lt;&lt; endl; for(double prob = .1; prob &lt; .99; prob += 0.1) { // Write the left column of the table cout &lt;&lt; setw(10) &lt;&lt; prob * 100 &lt;&lt; &quot;|&quot;; // Compute the actual data for(int start = 2; start &lt; 9; start++) { cout &lt;&lt; setw(10) &lt;&lt; walkProbability(start, 9, prob, 20000) * 100; } cout &lt;&lt; endl; } cout &lt;&lt; endl; }...
View Full Document

This note was uploaded on 10/28/2010 for the course CSCI 1113 taught by Professor Staff during the Spring '08 term at Minnesota.

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 Right Arrow Icon
Ask a homework question - tutors are online