calling functions randomly

Problem:
I have 5 user-defined functions a(),b(),c(),d() and e().In the main part i am to enter a value between 1-10.If the value I entered is between 1 and 5 then one of the function a() or b() or c() should be called once RANDOMLY.If value exceeds 5 the one of the 5 functions should be called RANDOMLY.I would also be interested in knowing if there is a way to make one of them rare ie FOR EG:- FUNCTION D() should have a chance to get invoked 1 out of 10 times etc.
pleaseee help me OH and if some one could do that please try to explain the concept behind it too ok!
thanks for the time,
cyberdude
You could put pointers to these functions (or std::function objects) in a container, such as vector, generate a random index, and call the function at that index:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <vector>
#include <functional>
#include <random>

void a() { std::cout << "a "; }
void b() { std::cout << "b "; }
void c() { std::cout << "c "; }
void d() { std::cout << "d "; }
void e() { std::cout << "e "; }

int main()
{
    std::vector<std::function<void()>> functions = {a,b,c,d,e};

    std::random_device rd;
    std::mt19937 gen(rd());
    std::discrete_distribution<> d({10, 10, 10, 1, 10});

    // call them randomly (with d() 10 times less likely)
    for(int n = 0; n < 30; ++n)
        functions[d(gen)]();
}


demo: http://ideone.com/vE2kub
Last edited on
thanks but could you explain the concept a further please?????????
Topic archived. No new replies allowed.