背景
最近写了一个对拍器,自认为对于对拍有一定见解,但今天$cjf$说如果用$srand(time(0))$,在卑微的Windows系统下一秒钟实际上只对了一组数据,因为$time(0)$在一秒钟内不会变化,写了个程序
试了一下,确实如此1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using namespace std;
int main(){
freopen("test.in","w",stdout);
int a = 0,las = 0,cnt = 0;
while (a==las){
srand(time(0));
a = rand();
if (!las) las = a;
cnt++;
}
cout<<cnt<<endl;
return 0;
}
cnt统计的是和最先一次rand出来的数相同的数的个数
cnt大概有1e7-2e7,可见数据生成器生成数据的不随机性(除非你的程序用时太久,不能在1s内跑完生成的数据)
显然,这会对对拍的效率产生严重影响,那么应该如何生成完全随机的数据呢?
方法
先用$srand$生成10个左右的随机数,然后就可以得到10个随机种子,再用它们生成随机数,同时运行程序,就可以得到真正的随机数了。
但这样有一个问题:生成的随机数都是5位数,所以在对拍几万个数据后,种子就是重复的了,那样就没有意义了,所以考虑生成更大的种子。
在这里给出一种方法:用两个$for$把种子乘起来当作种子,这样种子大概率就不同了。
具体传种子的方法读者可以自己实现,在这里给出一种方式:$freopen$1
2
3
4
5
6
7
8
9
10
11
12
using namespace std;
long long sed;
int main(){
freopen("seed.in","r",stdin);
cin>>sed;
srand((unsigned)sed);
/*
your code here
*/
return 0;
}
具体生成随机数的方法:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using namespace std;
long long rs[15];
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
while (1){
srand(time(0));
for (int i=1;i<=10;i++){
rs[i] = rand();
}
for (int i=1;i<10;i++){
for (int j=i+1;j<=10;j++){
ofstream output("seed.in");
output<<rs[i]*rs[j]<<endl;
system("1.exe");
}
}
}
return 0;
}
其实一般只随机10个数也可以,重复周期较长
附录
貌似不生成数据,单独使用$fc$比较文件很慢?(请读者自行测试100000行以上数据,本机测得$fc$比字符比较慢很多)