ykulah
ykulah

Reputation: 88

linux random function

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 ?

Upvotes: 2

Views: 1822

Answers (2)

Mats Petersson
Mats Petersson

Reputation: 129454

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];
}

Upvotes: 2

taskinoor
taskinoor

Reputation: 46037

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());
    }
}

Upvotes: 1

Related Questions