Frage

I am using Linux random() function to generate random message in CentOS 5.2. I want to reset the seed after 3 random calls. In other words I want the same output in 1st call and the 4th call. Is there any way to set rand() function to initial state ? or can do you know any other functions that I can do it ?

War es hilfreich?

Lösung

You can simply remember the seed and then use that to reset. Something like this in C:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
    int seed = time(NULL);
    int i;

    for (i = 0; i < 10; i++) {
        if (!(i % 3)) {
            srandom(seed);
        }

        printf("%d\n", random());
    }
}

Andere Tipps

If you just want to repeat three random numbers, then store three consecutive random numbers in an array and repeat to your hearts content.

int rand_arr[3];
int i;

srandom(time(NULL));   // Not the best way, but I'm lazy. 

for(i = 0; i < 3; i++)
{
   rand_arr[i] = rand();
}

for(i = 0; i < 10000; i++)
{
   printf("%d\n", rand_arr[i % 3];
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top