How to imply chances?

Hi,

Can you help me in my game, like the program will randomly choose the Emperor by chance 80%, slave 10%, and citizen 10%.

Here is my code,

srand (time(0));

int x = rand() % 3;

string cards[] = {"Emperor","Slave","Citizen"};

cout << cards[x] << endl;
Last edited on
What would you like us to help you with?
This is a C way of doing things, but...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <cstdlib>
#include <ctime>
#include <cstdio>
#include <iostream>
using namespace std;
int main()
{
   float probEmperor = 0.8f;
   float probSlave = 0.1f;
   float probCitizen = 0.1f;
   srand(time(NULL));
   int randnum = rand();
   cout << "randnum = " << randnum << " , randProb = " << float(randnum/float(RAND_MAX)) << endl;
   if( randnum < probEmperor*RAND_MAX )
      cout << "Emperor" << endl;
   else if ( randnum < (probEmperor+probSlave)*RAND_MAX )
      cout << "Slave" << endl;
   else
      cout << "Citizen" << endl;
   return 0;
}
Last edited on
C++11 rng approach
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <array>
#include <iostream>
#include <string>
#include <random>

int main()
{
    //http://en.cppreference.com/w/cpp/numeric/random/discrete_distribution
    std::array<std::string, 3> cards {"Emperor", "Slave", "Citizen"};
    std::discrete_distribution<> d   {    80,      10,        10   };
    
    std::mt19937 rng(std::random_device{}());

    std::cout << cards[d(rng)];
}
@MiiNiPaa Very good!
Topic archived. No new replies allowed.