Immort8lSp8rt8n
Immort8lSp8rt8n

Reputation: 21

Use rand() in C to get a different number every run without using time() or getpid()?

I am currently using the time() function inside srand() to generate a completely different and random number everytime the program is run.

srand(time(NULL));// chooses random seed for a different rand() every run 
  int n = 1 + rand() / (RAND_MAX / (100 - 1 + 1) + 1); // only generates numbers between 1 and 100
  printf("n = %d",n);
  int a = rand();
  printf("\na = %d",a);
  int b = rand();
  printf("\nb = %d",b);

Unfortunately, I have learned that I am not allowed to use time() or getpid(). Is there a way, using ONLY <stdio.h>, <stdlib.h> <assert.h> to generate a different random number every time the program is run?

Upvotes: 2

Views: 1698

Answers (2)

Phil
Phil

Reputation: 3

I'm kind of impressed I haven't seen this method anywhere else, one day I was digging through some github repos, and I found a projet using a method to randomly seed srand() (I forgot which repo).

I find it very elegant, I don't know too much about how the computer decides where each function should be, but this seems to work very well, if anyone wants to correct/clarify, it would be great.

void seed(void)
{
    return;
}

int main(void)
{
    srand((unsigned long)&seed);
    return (0);
}

This was how I found it, but I've tried passing it the address of main instead of the address of seed and it seems to work too.

You don't really need a specific seed function, any function will do.

Now I'm pretty sure this is not a reliable method for pseudo-randomness but for small projects that needs just the simples implementation of something "random", without using time(), getpid() or a block of code, this will more than do.

Upvotes: 0

רן מורסקי
רן מורסקי

Reputation: 134

I think someone has answered your question here: Generating random values without time.h

I think you can use a file with numbers and random your number from there, for example:

static int randomize_helper(FILE *in)
{
     unsigned int  seed;

    if (!in)
         return -1;

    if (fread(&seed, sizeof seed, 1, in) == 1) {
        fclose(in);
        srand(seed);
    return 0;
    }

    fclose(in);
    return -1;
}

static int randomize(void)
{
    if (!randomize_helper(fopen("/dev/urandom", "r")))
         return 0;
    if (!randomize_helper(fopen("/dev/arandom", "r")))
         return 0;
    if (!randomize_helper(fopen("/dev/random", "r")))
         return 0;

/* Other randomness sources (binary format)? */

/* No randomness sources found. */
    return -1;
}

and this is an example for main:

 int main(void)
 {
    int I;

    if (randomize())
        fprintf(stderr, "Warning: Could not find any sources for randomness.\n");

    for (i = 0; i < 10; i++)
        printf("%d\n", rand());

    return EXIT_SUCCESS;
}

Upvotes: 1

Related Questions