0

I'm trying to create a random array of random integers for a minesweeper game in C.

I'm trying to get random numbers from 1 to 64.

At the beginning of the main() function I initialize srand(time(NULL)). Later in the program, I use rand() in a loop to generate 8 random integers. In my initial test runs for other features, the numbers were perfectly random but as I ran more tests it started to give out integers 1-7 consistently and one random double-digit integer. Worth mentioning these tests are done on the Clion terminal. Is it a problem just because of where I run the program or something else?

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void eightByEight(int randArr[], int lower, int upper, int size);

int main() 
{
    int i, randNums[8];
    srand(time(NULL));
    eightByEight(randNums,1,64,8);
    for (i = 0; i < 8; i++)
    {
        printf("%d ", randNums[i]);
    }
    return 0;
}

void eightByEight(int randArr[], int lower, int upper, int size)
{
    int i,num;
    for (i = 0; i < size; i++) 
    {
         num = (rand() % (upper - lower + 1)) + lower;
         randArr[i] = num;
    }

} 
SiiilverSurfer
  • 999
  • 1
  • 6
  • 12

1 Answers1

3

The time function gives you the current time in seconds since the epoch. If you run the program twice in a short period of time, the time function will return the same value on both runs and you'll therefore get the same sequence of random values.

dbush
  • 205,898
  • 23
  • 218
  • 273