0

So, my c program will print out how deep Binary search tree is after inserting N random numbers, I wanted to run it 500 times and save the result in the text file.

After compiling, gcc -Wall myProgram main.c. I tried ./myProgram and it returns different result every time which is 9012,9023,9231,9523,9533..., but as soon as I use bash loop

for i in {1..500} do ./myProgram >> text.txt done

It always returns 500 same number. I initially thought there is problem with my C program, but when I run it on IDE or just running it once works without a problem

I forgot to mention that my c program uses time.h for random number generation, could it be the problem?

srand(time(NULL));

T = Initialize();
T = MakeEmpty(T);

int array[N];

for (int i = 0; i < N; i++) {     // fill array
    array[i] = i;
}

for (int k = 0; k < N; k++) {    // shuffle array
    int temp = array[k];
    int randomIndex = rand() % N;
    array[k]           = array[randomIndex];
    array[randomIndex] = temp;
}

for (j = 0; j < N; j++){
    //printf("%d\n", array[j]);
    T = Insert(array[j], T);
}
Dongho Han
  • 97
  • 3
  • 9
  • 2
    Can't tell without code, but it may be that you are seeding the random number generator with the current time in seconds and this bash script is running this program all within the same second. – afic Feb 24 '18 at 20:10
  • yes, I edited the question again, I believe that is what's happening. Is there a way for me to fix random number generator? – Dongho Han Feb 24 '18 at 20:11
  • perhaps have some entropy input into your program that your bash script will pass in via command line argument. – afic Feb 24 '18 at 20:12
  • `time` only changes every second. If your program runs more than 500 times per second, chances are all of your random sequences will be the same. – n. m. could be an AI Feb 24 '18 at 20:18

1 Answers1

0

srand(time(NULL)) will cause all of your random numbers to be the same if this statement is ran within the same second. Consider taking a number in via command line argument and using it to manipulate your seed. For example:

int main(int argc, char **argv)
{
    int entropy;
    if(argc != 2)
    {
         srand(time(NULL));
    }
    else
    {
         entropy = atoi(argv[1]);
         srand(time(NULL) + entropy);
    }
    //... rest of code ...
}

Then your bash script code do something similar to:

for i in {1..500} do ./myProgram i >> text.txt done

afic
  • 500
  • 4
  • 13