ACM对拍程序

对拍

不停的随机生成测试数据,分别运行两个程序并对比其结果。这个任务被形象的称为对拍 。

流程

(1)编写好生成随机数程序(r.cpp),我的程序(a.cpp),标准程序(b.cpp),编译

(2)将生成的r.exe、a.exe、b.exe以及批处理脚本(.bat)放到同一个文件夹下

(3)运行批处理脚本,发现不同时会自动暂停

生成随机数据

这里只写产生整数,产生小数和字符串只要在这个基础上简单修改就行。

 1 #include
 2 #include
 3 #include
4 #define random(a,b) ((a)+rand()%((b)-(a)+1)) //random(a,b)生成[a,b]的随机整数 5 int main( ) 6 { 7 8 srand( time( NULL ) ); 9 int t,n = 10000 ; 10 while( n-- ) 11 { 12 printf("%d\n",rand() ); //rand()的范围是0~RAND_MAX(即[0,32767]) 13 } 14 return 0; 15 }

Windows下的批处理

 1 @echo off        //关掉输入显示,否则所有的命令也会显示出来
 2 
 3 :loop    
 4     rand.exe > in.txt                        //生成随机输入
 5     my.exe < in.txt  > myout.txt       
 6     std.exe < in.txt  > stdout.txt
 7     fc myout.txt stdout.txt                   //比较文件
 8 if not errorlevel 1   goto loop               //不为1继续循环,fc在文件相同时返回0,不同时返回1
 9 pause                //不同时暂停,你可以看in.txt里的数据
10 goto loop            //看完数据,按任意键结束暂停,继续循环

用文本编辑器(记事本就行)写好,保存为.bat 后缀名

Linux下的Bash脚本

1 #!/bin/bash
2 while true; do
3     ./r > input                          //生成随机事件
4     ./a < input > output.a
5     ./b < input > output.b
6     diff output.a output.b           //文本比较
7     if [ $? -ne 0 ] ; then break;fi     //判断返回值
8 done

同样用文本编辑器写好保存为.s(例如cmp.sh),在执行chmod +x cmp.sh,即可用./cmp.sh来执行它,当然扩展名也不是必需的,完全可以用不带扩展名的cmp命名。

随机数算法改进

上面的随机数的随机数算法中,生成随机种子函数参数 time(NULL)

 随机数算法:

 1 #include
 2 using namespace std;
 3 #define random(a,b) ((a)+rand()%((b)-(a)+1))
 4 
 5 stringstream ss;
 6 
 7 int main( int argc, char *argv[] )
 8 { 
 9     int seed=time(NULL);
10     if(argc > 1)//如果有参数
11     {
12         ss.clear();
13         ss<1];
14         ss>>seed;  //把参数转换成整数赋值给seed
15     }
16     srand(seed);
17     //以上为随机数初始化,请勿修改
18     //random(a,b)生成[a,b]的随机整数
19 
20     //以下写你自己的数据生成代码 
21     printf("1\n");
22     int n=10;
23     int m=random(1,20);
24     printf("%d %d\n",n,m);
25     for(int i=0 ; ii)
26     {
27         printf(" %d ",random(0,m));
28     }
29     printf("\n");
30     return 0;
31 }

批处理脚本:

1 @echo off  
2 :loop  
3     rand.exe %random% > data.in
4     std.exe < data.in > std.out
5     my.exe < data.in > my.out
6     fc my.out std.out 
7 if not errorlevel 1 goto loop  
8 pause
9 goto loop

 参考链接:

(1)ACM/OI对拍程序的写法:https://blog.csdn.net/wlx65003/article/details/51149196

(2)ACM对拍程序:https://blog.csdn.net/churehill123/article/details/19647579

 (3)C语言中rand()函数的用法笔记:https://blog.csdn.net/chikey/article/details/66970397

转载于:https://www.cnblogs.com/lfri/p/9696464.html

你可能感兴趣的:(ACM对拍程序)