0

I want to generate 10 random numbers in c++ between 1 and 3 inside a loop such that 1 comes the most times (say 50% times), then 2 (30% times) and then 3(20% times). Is it possible to do so?

I have made the following code to get the random numbers between 1 and 3 but how will I add the probabilities?

#include <iostream>
#include <windows.h>
#include "time.h"
int main(int argc, char*argv[])
{
    srand ( time(NULL) );
    for (int t = 0; t < 10; t++)
    {
        int random_x;

        random_x = rand() % 3+1;
        std::cout << "\nRandom X = " << random_x << std::endl;
    }
    Sleep(50000);
    return 0;
}

1 Answers1

-1

You can do something like this (in pseudo code)

x=random(0,100)
if(x<p1){
  y=1;
} else if (x<p2)
  y=2
} else{
  y=3
}

p1 is the change for 1
p2-p1 is the change for 2
and 100-p2 is the change for 3

djxyz
  • 125
  • 4