算法竞赛--算法练习工具之代码对拍

我们在练习算法时,很多时候可以将自己的代码跟网上提供的标准代码比对,既可以学习别人的写法,另外也可以找出自己代码存在的问题,方便调试。对拍就是一种很好的调试代码的方式。用正确的代码找出使错误代码出错的数据,或者用效率低的正确代码验证效率高的代码的正确性

对拍总共需要四份代码

1.自己的代码 my.cpp

2.正确的代码 correct.cpp

3.数据生成器 data.cpp

4.比较器 checker.cpp

我们看一个例子:

美国总统奥巴马不仅呼吁所有人都学习编程,甚至以身作则编写代码,成为美国历史上首位编写计算机代码的总统。2014 年底,为庆祝“计算机科学教育周”正式启动,奥巴马编写了很简单的计算机代码:在屏幕上画一个正方形。现在你也跟他一起画吧!

输入格式:

输入在一行中给出正方形边长 N(3≤N≤20)和组成正方形边的某种字符 C,间隔一个空格。

输出格式:

输出由给定字符 C 画出的正方形。但是注意到行间距比列间距大,所以为了让结果看上去更像正方形,我们输出的行数实际上是列数的 50%(四舍五入取整)。

样例输入:

1
10 a

样例输出:

1
2
3
4
5
aaaaaaaaaa
a a
a a
a a
aaaaaaaaaa

(1)首先写出自己的代码:

在自己的代码主函数加入下面代码:
1
2
freopen("in.in","r",stdin);				//从in.in文件中读数据
freopen("out1.out","w",stdout); //将结果输出到out1.out文件中

my.cpp如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <stdio.h>
char A[25][25];
int main()
{
freopen("in.in","r",stdin);
freopen("out1.out","w",stdout);
int N,M;
char c;
scanf("%d %c",&N,&c);
N%2==0?M=N/2:M=N/2+1;
for(int i=0;i<N;i++)
{
A[0][i]=c;
A[M-1][i]=c;
}
for(int i=1;i<=M-2;i++)
{
A[i][N-1]=c;
A[i][0]=c;
}
for(int i=0;i<M;i++)
{
for(int j=0;j<N;j++)
printf("%c",A[i][j]=='\0'?' ':c);
printf("\n");
}
return 0;
}

(2)找一份可以AC的代码:

在代码主函数加入下面代码:
1
2
freopen("in.in","r",stdin);			//从in.in文件中读数据
freopen("out2.out","w",stdou //将结果输出到out2.out文件中

correct.cpp如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include<stdio.h>
#include<iostream>
#include<string>
#include<map>
#include<vector>
#include<set>
#include<algorithm>
using namespace std;
int main()
{
freopen("in.in","r",stdin);
freopen("out2.out","w",stdout);
int N; string c;
cin >> N>>c;
int rows;
if (N % 2 == 0)
rows = N / 2;
else
rows = N / 2 + 1;
for (int i = 0; i < rows; i++)
{
if (i == 0 || i == rows - 1)
{
for (int j = 0; j < N; j++)
cout << c;
cout << endl;
}
else
{
for (int j = 0; j < N; j++)
if (j == 0 || j == N - 1)
cout << c;
else
cout << " ";
cout << endl;
}
}
return 0;
}

(3)制作数据生成器:

data.cpp如下:

1
2
3
4
5
6
7
8
9
10
11
12
#include<ctime>
#include<cstdio>
#include<cstdlib>
int main()
{
freopen("in.in","w",stdout);
srand(time(0));//用当前时间来设定rand函数所用的随机数产生演算法的种子值。
int n=rand()%20+3;//产生一个3-23的数
int m=rand()%60+40;//产生一个40-100的数 用来产生ASCII码为40-100的字符
printf("%d %c\n",n,(char)(m));
return 0;
}

(4)制作比较器:

checker.cpp如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<cstdlib>
#include<windows.h>
int main()
{
while(1){
system("data.exe");
system("my.exe");
system("correct.exe");
if(system("fc out1.out out2.out")){
break;
}
}
return 0;
}

(1)将四个代码保存在同一目录下。

(2)先分别运行my.cpp和correct.cpp生成out1.out文件和out2.out文件及对应的exe文件。

(3)运行data.cpp生成in.in文件

(4)运行check.cpp进行比较

两文件的输出不同程序就会停止,可以去in.in文件中找到出错的测试数据,一般1-2秒就可检查出错误。

下图为正在运行中的程序,且未出现错误

图

小礼物走一个哟
0%