在算法竞赛中编写算法时需要不断修改测试用例和算法代码,还要不断重新提交代码到服务器,如果算法代码,和测试代码全部放到一起,将会非常不方便,本文介绍一种本人使用的简单方法,实现测试代码和算法代码的隔离
我的项目是一个 gradle 项目,其配置如下
plugins {
id 'java'
}
group 'org.example'
version '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
dependencies {
implementation 'junit:junit:4.13.1'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
}
test {
useJUnitPlatform()
}
算法类:
import java.io.*;
import java.util.*;
// 这是算法源代码,在向oj提交代码时我们直接提交这个文件即可
public class Main {
public static void main(String[] args) {
// 在oj正式环境中,使用 System.in, System.out
solution(System.in, System.out);
}
// 该方法既可以被测试方法调用,也可以被main调用
public static void solution(InputStream i, PrintStream o) {
Scanner scanner = new Scanner(i);
String data = scanner.nextLine();
// processing data...
// public result
o.println("not complete");
o.println();
}
}
测试代码:
import org.junit.jupiter.api.Test;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
// 这里是测试代码
class MainTest {
private static final String TEST_CASES = """
(11,) (11,L) ()
(3,L) (4,R) ()
""";
private static final String ANSWERS = """
5 4 8 11 13 4 7 2 1
not complete
""";
private final ByteBuffer bf = ByteBuffer.allocate(8 * 1024);
// 在本地测试时执行这个测试方法
@Test
void solution() {
// 将字符串作为输入,也可以将文件内容作为输入
InputStream in = new ByteArrayInputStream(TEST_CASES.getBytes(StandardCharsets.UTF_8));
// 将输出重定向到内存buffer中,也可以重定向到文件
PrintStream out = new PrintStream(new OutputStream() {
@Override
public void write(int b) {
bf.putInt(b);
}
@Override
public void write(byte[] b) {
bf.put(b);
}
@Override
public void write(byte[] b, int off, int len) {
bf.put(b, off, len);
}
});
// 执行测试并记录时间
long start = System.currentTimeMillis();
try {
Main.solution(in, out);
} catch (Throwable e) {
e.printStackTrace();
}
long interval = System.currentTimeMillis() - start;
// 关闭流
closeClosable(in);
closeClosable(out);
// 输出结果
bf.flip();
String yourAnswer = new String(bf.array(), 0, bf.limit());
l("your ans:n" + yourAnswer);
l("yes ans:n" + ANSWERS);
// 输出结果和预期进行比较
String youAnswerPlain = yourAnswer.replaceAll("\s*", "");
String yesAnswerPlain = ANSWERS.replaceAll("\s*", "");
boolean right = false;
if (!youAnswerPlain.equals(yesAnswerPlain)) {
l("Wrong Answer!n");
l(youAnswerPlain + "n");
l(yesAnswerPlain + "n");
} else if (!yourAnswer.equals(ANSWERS)) {
l("Presentation Error!");
} else {
right = true;
}
// 输出执行时长
l(String.format("nnTime Cost: %ds%dmsn", interval / 1000, interval % 1000));
assert right;
}
// 本地打印
private static void l(Object o) {
System.out.print(o.toString());
}
private static void closeClosable(Closeable c) {
try {
c.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
我们还可以对结果做更加精细的分析,比如是哪个case没有通过等。
仅供参考,谢谢!



