- Joined
- 11/5/14
- Messages
- 315
- Points
- 53
Hi all,
I was trying to run a small simulation of the 6/52 Lotto and show that the empirical probability of winning approaches the theoretical probability. Now, C++ uniform_int_distribution ggenerates samples that obeys Uniform(a,b) statistically. If I have to sample from a population without replacement, I must use another technique.
I googled to find that an easy way to implement this would (sample the 6 numbers on a ticket from {1,2,3,...,52} without replacement) be to std::shuffle on an std::array<int>. But, is there any other native way to do it?
This is just for fun! The code so far:
Thanks,
Quasar.
I was trying to run a small simulation of the 6/52 Lotto and show that the empirical probability of winning approaches the theoretical probability. Now, C++ uniform_int_distribution ggenerates samples that obeys Uniform(a,b) statistically. If I have to sample from a population without replacement, I must use another technique.
I googled to find that an easy way to implement this would (sample the 6 numbers on a ticket from {1,2,3,...,52} without replacement) be to std::shuffle on an std::array<int>. But, is there any other native way to do it?
This is just for fun! The code so far:
Code:
#include <iostream>
#include <random>
#include <ctime>
double choose(int n, int k);
int main()
{
int n,w,b,k, no_of_trials;
std::cout << "\n*************************************************************************\n";
std::cout << "\n***** Welcome to Lotto Sim *****\n";
std::cout << "\n*************************************************************************\n";
std::cout << "\nEnter the total number of possible lottery numbers n : ";
std::cin >> n;
std::cout << "\nEnter the total number of winning numbers w : ";
std::cin >> w;
b = n - w;
std::cout << "\nEnter k, to match k of the winning numbers : ";
std::cin >> k;
std::cout << "\nTheoretical odds of winning the game are : ";
/*Sample without replacement, hypergeometric */
std::cout << "1 in " << choose(n, w)/(choose(w,k)*choose(b,w-k));
std::cout << "\nEnter the number of trials to run : ";
std::cin >> no_of_trials;
/*Mersenne twister is used to generate pseudo-random numbers.
The RNG is initialized using a seed value and passed to distribution object.*/
typedef std::mt19937 myRNG;
myRNG my_random_num_generator;
int seed_val = (int) time(0);
my_random_num_generator.seed(seed_val);
std::uniform_int_distribution<int> uniform(1, n);
int* winning_ticket = new int[w];
std::cout << "\nThe winning ticket is : ";
for (int i = 0; i < w; i++)
{
winning_ticket[i] = uniform(my_random_num_generator);
std::cout << winning_ticket[i] << " ";
}
std::cin.get();
std::cin.get();
return 0;
}
double choose(int n, int k)
{
double accum = 1.0;
int m=n;
for (int i = 1; i <=m-k; i++)
{
accum = accum * n/ (n-k);
n--;
}
return accum;
}
Thanks,
Quasar.