- #1
sandy.bridge
- 798
- 1
Homework Statement
The idea is that the program asks the console user to provide them with a number that tells the program how many different colors of balls are to be used. Then, a ball is randomly drawn from a jar. That ball is put back in the jar, and balls are drawn until the same ball as the first is drawn again. This act is averaged over N times to get a good average (value of N is also provided by the user).
Now, it is suggested that we are to be within 1/100th of the following results:
How many different ball colors are there? 50
How many trials would you like to run? 100000
Average number of balls drawn to get a duplicate over 100000 trials: 9.52394
The Attempt at a Solution
I believe my issue lies in my use of the random function. Here is the code:
PHP:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int random(int k)
{
int y = rand() % k, i;
for (i = 1;; i++)
{
int x = rand() % k;
if (y == x)
{
break;
}
}
return i;
}
int main() {
int i = 0, j, k, sum = 0;
srand(time(0));
cout << "Please enter the number of colours: ";
cin >> k;
cout << "Please enter the number of trials: ";
cin >> j;
{while (i < j)
{
sum = sum + random(k);
i++;
} cout << sum/k;}
return 0;
}
What happens is averaging it over N trials results in the average approaching the value of how ever many balls the user chose to use.