Random numbers

0 Glenn Walker · September 20, 2014
When I have a need to generate random numbers I have a function I use as can be seen below:

    int randomNumGen(int randomNum)
    {
        srand(time(0));
        randomNum = (rand() % 5);//set the number after the mod to whatever required.

        return randomNum;
    }

The function works just fine most of the time.  However, I sometimes need several random numbers.  Again, no problem except when I need to call the function repeatedly.  What happens is that not enough time goes by for the function to move on to the next time point.  Basically, the seed generated is the same.  So, say if I am calling the function 3 times in a loop from another function I will get the same number 3 times.  Of course I can place a tool to allow some time to go by between calls, but the time is significant and that seems very needless.

Is there a way to set up a random number generator that can be called repeatedly and move the seed along without having to sacrifice slow the program execution down?

Post a Reply

Replies

Oldest  Newest  Rating
0 Çağlan Turgut · September 20, 2014
#include <iostream>

using namespace std;

int main()
{

int rand;
int rand2;

srand(time(0));

rand = std::rand() % 100;

srand(time(0) + 11); //change the seed a little bit instead of waiting. You can create another random algoritm though if you do not want to  directly type a number like "11".

rand2 = std::rand() % 100;

std::cout << "rand:" << rand<< std::endl << "rand2:" << rand2 << std::endl;

}


This is what I can think of right now :). I just like the number 11 so don't mind that there's nothing special.
0 Franz Schmidt · September 20, 2014
I also had this problem a while ago  XD
It's easy you just have to multiply the time value with another random value.
I use _getpid():

#include "stdio.h"
#include "conio.h"
#include "process.h" //for _getpid()
#include "time.h"
#include <iostream>
using namespace std;

int main(){
srand(time(0) * _getpid());
while(1){
cout << rand() % 5 << endl;
}

_getch();
return 0;
}



Btw: Use srand only once in a program. It won't get more random if you use it multiple times.
0 Glenn Walker · September 20, 2014
Thanks.  Both of those work quite well and I will use those methods.  I also found that by taking the seed out of the loop that repeatedly runs the random number generator I get the same effect.  The only problem I have left is the fact that the range of my random numbers is only 5 and I will get a high percentage (60% approximately) of repeats for a loop run three times.  That can easily be solved by adjusting the random number value with some branches for repeat random numbers.
  • 1

C++

107,224 followers
About

Used in many types of software including music players, video games, and many large scale applications.

Links
Moderators
Bucky Roberts Administrator