ACM對拍程序

對拍c++

不停的隨機生成測試數據,分別運行兩個程序並對比其結果。這個任務被形象的稱爲對拍 。算法

流程bash

(1)編寫好生成隨機數程序(r.cpp),個人程序(a.cpp),標準程序(b.cpp),編譯dom

(2)將生成的r.exe、a.exe、b.exe以及批處理腳本(.bat)放到同一個文件夾下編輯器

(3)運行批處理腳本,發現不一樣時會自動暫停函數

生成隨機數據oop

這裏只寫產生整數,產生小數和字符串只要在這個基礎上簡單修改就行。測試

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<time.h>
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下的批處理spa

 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 後綴名.net

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<bits/stdc++.h>
 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<<argv[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 ; i<n ; ++i)
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

相關文章
相關標籤/搜索