對拍器的功能就是可以隨機造數據對比兩份代碼的輸入輸出,來看自己哪裏錯了,一般用於做oj題目。
本來想用java來寫,那個system命令執行不了g++(可能是我使用的方法不對)。
所以改用python寫了個僅限於對拍C/C++,其實實現很簡單就是通過cmd來編譯運行cpp,並獲取運行結果
進行對比。
講一下具體運用場景,比如你在寫a + b這道題下面是正確代碼:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int a, b;
cin >> a >> b;
cout << a + b << endl;
return 0;
}
沒準你寫錯了,寫成了這個:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int a, b;
cin >> a >> b;
if (a == 1 && b == 1)
cout << a + b + 1 << endl;
else
cout << a + b << endl;
return 0;
}
現在你不知道哪裏錯了,萬念俱灰,這時你的朋友給了你一份正確代碼,你想知道哪裏錯了。
你就可以隨機造些數據來看自己代碼跟他的代碼輸出差異。
沒錯下面這份py就可以實現這個功能。
A,B分別放上兩份要對拍的代碼,spath存放樣例數據,brk是最大對拍次數,get函數用來生成你要造的數據
當然造的數據格式要跟題目所規定的方式一樣。
import os
import random
import sys
A = "D:\sublime\A" #A文件位置
B = "D:\sublime\B" #B文件位置
spath = "D:\input.txt" #生成數據文件
brk = 500 #最多對拍次數
def init(): #初始化編譯文件
os.system("g++ " + A + ".cpp -o " + A + ".exe -std=c++11")
os.system("g++ " + B + ".cpp -o " + B + ".exe -std=c++11")
def rand(l, r):
return str(random.randint(l, r))
def crand(s):
if s == "":
print("隨機字符長度不能爲空")
sys.exit(0)
else:
s = str(s)
len1 = len(str(s))
return s[int(rand(0, len1 - 1))]
def get(): #隨機函數
p = open("D:\input.txt", "w")
s = ""
s += rand(1, 4) + " " + rand(1, 4)
p.write(s)
return s
init() #c++別忘了初始化
cnt = 0 #初始化對拍次數
while True:
cnt += 1
sample = get()
a = os.popen(A + ".exe < " + spath)
b = os.popen(B + ".exe < " + spath)
ansA = a.read()
ansB = b.read()
if ansA != ansB:
print("sample" + str(cnt) + ":Wrong!\n" + sample + '\n')
print("ansA:\n" + ansA)
print("ansB:\n" + ansB)
break
else:
if cnt != brk:
print("sample" + str(cnt) + ":Right!")
else:
print(str(brk) + "組數據未有錯誤,停止對拍")
break
input()
如果你有pycharm,你可以直接用pycharm來運行這份代碼。
pycharm運行結果:
在這份代碼裏面get函數中先是隨機了一個1到4的數字,又隨機了一個1到4的數字
然後在同時隨機到兩個數字爲1的時候出現了錯誤,所以這個時候你就會發現你代碼
對於1 1這個數據跑不過去,然後你一改就對了。
如果你沒有安裝pycharm,你可以新建一個.py文件,當然你電腦要安裝了python纔行,
然後把對拍代碼放進去,右擊-打開方式-python,然後運行即可。
對於隨機生成字符
crand("字符")
例如你要生成的字符有a,b,c
你需要crand("abc"),當然你如果crand("aaaaabc"),那麼隨機到字符a的概率會
明顯大於其他字符。
例如下面的兩份代碼,要求是無論輸入什麼都輸出”YES“。
正確代碼:
#include <stdio.h>
#include <string.h>
#include <unordered_map>
int main()
{
char s[10];
scanf("%s", s);
puts("YES");
return 0;
}
你又寫錯了:
#include <stdio.h>
#include <string.h>
#include <unordered_map>
int main()
{
char s[10];
scanf("%s", s);
if (strcmp(s, "aaa") == 0)
puts("NO");
else
puts("YES");
return 0;
}
在萬念俱灰的時候,你的朋友又給了你一份代碼。
-----
現在你要把對拍代碼裏面的隨機函數修改成隨機輸出字符,假設題目中是輸入一個長度爲3的
字符串,裏面含有a,b,c,d,e五個字符。你的隨機函數就可以按如下來生成,返回的s即是你生成的數據。
def get(): #隨機函數
p = open("D:\input.txt", "w")
s = ""
for i in range(1, 4):
s += crand("abcde")
p.write(s)
return s
這題的對拍結果,當樣例輸入的是”aaa“時, 你又發現你的程序出現了錯誤,然後你一改就對了。
pycharm運行結果:
隨機出來的數據是由你自己來做的,一般是按照題目要求。
現在功能還有點薄弱,沒加special judge。