0

so im trying to make a random number generator that will give me 1, 2 or 3 but for some reason it always give me 3. sorry its in french but i figured it didnt really matter. also tell me if something is missing its my first time posting here.

#include <iostream>
#include <fstream>
#include <string>
#include <ctime>

RPC choixOrdi()
{
    int min = 1;
    int max = 3;
    int randNum = rand() % (max - min + 1) + min;
    return convertirRandNum(randNum);
    
}

RPC convertirRandNum(int randNum)
{
    switch (randNum)
    {
    case 1:
        return RPC::Roche;
        break;
    case 2:
        return RPC::Papier;
        break;
    case 3:
        return RPC::Ciseaux;
        break;
    default:
        return RPC::Invalid;
    }
}```

1 Answers1

0

The problem is that the random is not properly seeded. As current computer cannot generate a true random number, it generates the deterministic pseudo-random number sequence, which has to be initialized by number you choice. It is called seeding. One solution is that you seed the rand() by current time using srand(time(NULL)). such as:

RPC choixOrdi()
{
    int min = 1;
    int max = 3;
    srand(time(NULL));
    int randNum = rand() % (max - min + 1) + min;
    return convertirRandNum(randNum);
    
}

There can be more improvement. You can just throw away the C-style random generator, and use std::random_device, std::mt19937 and so on. You can find examples here: https://en.cppreference.com/w/cpp/numeric/random

EDIT: As someone else pointed out, seeding rand(time(NULL)) each time when the function is called is really a bad choice, especially when you have multiple clients calls the function simultaneously. If random_device is available to you, this can be other workaround:

RPC choixOrdi()
{
    int min = 1;
    int max = 3;
    static std::random_device rd;
    static std::uniform_int_distribution<int> dist(min, max);
    return convertirRandNum(dist(rd));
}
K.R.Park
  • 1,015
  • 1
  • 4
  • 18
  • 1
    it's a bad idea to call `srand()` in a function like that. See [srand() — why call it only once?](https://stackoverflow.com/q/7343833/995714) – phuclv Feb 18 '22 at 03:48
  • @phuclv Oh yes, however, as there was no place to put srand(), I had no choice. If there is main() function, I suggest OP to call it at the very first line of main() function, and do not call it again. – K.R.Park Feb 18 '22 at 03:49
  • Thank you very much for the response ! i managed to figure it out, it was a problem in my main function and after some light modifications its working. – Olivier Verreault Feb 18 '22 at 15:05
  • @OlivierVerreault Um… Will you mark this as an answer then? – K.R.Park Feb 18 '22 at 18:55