1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
|
// Programmieren 1, Praktikum 4, Aufgabe 4
// Sven Eisenhauer
// 14.12.2004
//
// file: main.cpp
//
// purpose: Simulate a Galton Board
//
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
#include <iomanip>
using std::setprecision;
using std::setw;
// contains function prototypes for functions srand and rand
#include <cstdlib>
#include <ctime>
const int maxBoxes=100;
const int minBoxes=1;
int fall(int &,int &);
void getInput(int &,int &, char &);
void textOutput(int[], const int, const int);
void graphicalOutput(int[], const int, const int);
int main()
{
srand(time(0));
int nrBalls;
int minBox,maxBox,nrBox;
int box;
int result[maxBoxes+1]={0};
char outputMode;
getInput(nrBalls,nrBox,outputMode);
for (int i=1;i<=nrBalls;i++)
{
minBox=minBoxes;
maxBox=nrBox;
box=fall(minBox,maxBox);
result[box]++;
}
if (outputMode=='t' || outputMode=='T')
textOutput(result,nrBalls,nrBox);
else
graphicalOutput(result,nrBalls,nrBox);
return 0;
}// end function main
void getInput(int& nrBa, int& nrBo, char &outpMode)
{
cout << "Please enter number of boxes (max." << maxBoxes <<"): ";
cin>>nrBo;
cout << "Please enter number of balls: ";
cin>>nrBa;
cout << "Please enter output mode: [T/t] table, [G/g] graphical: ";
cin >> outpMode;
}// end function getInput
int fall(int &minB, int &maxB)
{
// if we are not over last 2 boxes
if((maxB-minB)>1)
{
if (0==rand()%2)
// ball falls to the right => we cannot reach the most left box anymore
minB++;
else
// ball falls to the left => we cannot reach the most right box anymore
maxB--;
fall(minB,maxB);
//return 0;
}
// only 2 possible boxes left... the base case
else
{
if (0==rand()%2)
// left box
return minB;
else
// right box
return maxB;
}
}
void textOutput(int resArray[], const int balls,const int nrBox)
{
//int sum=0;
cout << endl << setw(10) << "Box" << setw(10) << "Balls" << setw(16) << "Norm." <<endl;
for (int n=1;n<=nrBox;n++)
{
cout << setw(10) << n << setw(10) << resArray[n] << setw(16)<<static_cast <double>(resArray[n])/balls<<endl;
// sum+=resArray[n];
}
//cout << endl << "Sum: " << sum << endl << endl;
}// end function textOutput
void graphicalOutput(int resArray[], const int balls, const int nrBox)
{
const int maxColumns=75;
for (int n=1;n<=nrBox;n++)
{
cout << setw(2) << n << ": ";
for (int i=0;i<static_cast <int>(((static_cast <double> (resArray[n]))/balls)*maxColumns);i++)
cout<<"*";
cout << endl;
}
}// end function graphicalOutput
|