I’m using ubuntu 10.10 and I want to test my C++ program with several random tests, so I want to generate them. I wrote generator:
// gen.cpp
#include <iostream>
#include <cstdio>
#include <ctime>
#include <cstdlib>
using namespace std;
int main() {
srand(time(NULL));
int n=rand()%100;
int k=rand()%n+1;
printf("%d %d\n", n,k);
for(int i=0; i<n; i++) {
int a = rand()%100;
printf("%d\n", a);
}
return 0;
}
Then typed in terminal:
for((i=0; i<10; i++)); do ./gen > $i.in; done
But the result is that all *.in files contain the same numbers. When I type:
./gen > 0.in
./gen > 1.in
and so on, then everything is OK – all *.in files are different. But I don’t want to create them manually every time I need them. I want to do this in loop. Why is that and how can I fix this?
You need to put a delay in your
bashloop so that it’s not using the same seed every time. Because you’re usingtime()as the seed, all executions in the same second will give you the same sequence.A
sleepshould do the trick, something like: