I have to generate a dice roll with a probability and the probability is determined by the user entering the weight of each side. How would I generate random numbers with probability.
void input()
{
int side;
cout << "Enter the sides for a die (2 or greater).\n";
cin >> side ;
while (side < 2)
{
cout << "Enter the sides for a die (2 or greater).\n";
cin >> side;
}
double weight[side-1];
double *p;
p = weight;
for (int i=0; i<=(side-1); i++)
{
cout << "Enter the weights for each side (greater than 0).\n";
cin >> *p;
if (*p > 0)
{
weight[i] = *p;
}
while (*p <= 0)
{
cout << "Invalid weight entered. Try again.\n";
cout << "Enter the weights for each side (greater than 0).\n";
cin >> *p;
}
}
roll(side, p);
menu();
}
int roll(int sides, double *weights)
{
int roll, output;
cout << "Please enter the amounts of times you want to roll the dice (greater than 0).\n";
cin >> roll;
srand(time(0));
if (roll>=1 && roll<=sides)
{
output = (rand() % sides) + 1;
}
while (roll<1 || roll>sides)
{
cout << "Error. Please try again.";
cout << "Please enter the amounts of times you want to roll the dice (greater than 0).\n";
cin >> roll;
}
}
#include <iostream>
#include <vector>
#include <ctime>
#include <cstdlib>
#include <cmath>
usingnamespace std;
//======================================================================
// Return the upper limits of each partition of random numbers
vector<int> weightToLimit( const vector<double> &weight )
{
int N = weight.size();
// Find cumulative weights
vector<double> sumWeight( N );
for ( int i = 0; i < N; i++ ) sumWeight[i] = ( i ? sumWeight[i-1] : 0 ) + weight[i];
// Split a CONTINUOUS number range -0.5 to RAND_MAX + 0.5, then round DOWN to get upper limits (inc. -1)
vector<int> upperLimit( N );
for ( int i = 0; i < N; i++ ) upperLimit[i] = floor( -0.5 + ( 1.0 + RAND_MAX ) * sumWeight[i] / sumWeight[N-1] );
return upperLimit;
}
//======================================================================
// Return the result of one roll (between 0 and SIDES - 1)
int roll( const vector<int> &upperLimit )
{
int r = rand();
int i = 0;
while ( upperLimit[i] < r ) i++;
return i;
}
//======================================================================
int main()
{
srand( time( 0 ) );
// vector<double> weight = { 1, 1, 1, 1, 1, 1 }; // Unbiased 6-sided die
vector<double> weight = { 0, 0, 1, 1, 2, 2 }; // Very biased die
int SIDES = weight.size();
int NROLLS = 1000000;
vector<int> number( SIDES, 0 );
vector<int> upperLimit = weightToLimit( weight );
for ( int r = 1; r <= NROLLS; r++ ) number[ roll( upperLimit ) ]++;
cout << "Percentages:\n";
for ( int s = 1; s <= SIDES; s++ )
{
cout << s << '\t' << 100.0 * number[s-1] / NROLLS << '\n';
}
}