【开发一个OnlineJudge网站】OnlineJudge判题



前言

本文章是使用Java实现的OnlineJudge,实现了Java在线的判题。

适用于想实现一些和学校的oj差不多的网站,练手、大作业的同学,可以参考一下Runtime.getRuntime().exec(command)和反射的实现代码,并且用到了线程池。

在返回状态上,将会涉及到多种状态的判定:
Accept 通过
Wrong Answer 答案错误
Compile Error 编译错误
Runtime Error 运行错误
Time Limit Exceeded 时间超限
OOM内存超限,技术不太行没做

1.提交的代码封装成可执行文件

如果像牛客一样,那么封装成可执行文件比较简单,直接当文件写下来,java拿Runtime.getRuntime().exec(command)编译和执行就完事了。
以下是用Runtime.getRuntime().exec(command)的实现:

编译,不是所有语言都需要编译,所以分开了编译和执行,这里实现了java的编译:

package handler;

public class CompileFileHandler{
    public static boolean compileJava(String id){
        try{
            Process process = Runtime.getRuntime().exec("javac " + FileHandler.idToFilePath(id));
            process.waitFor();
            process.destroy();
            if(!FileHandler.isClassFileExists(id)){
                return false;
            }
        }catch(Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}

执行文件,实现执行java文件:

package handler;

import java.io.*;
import java.util.concurrent.TimeUnit;


public class ExecuteFileHandler {
    public static String executeJava(String id, String input){
        StringBuilder result = new StringBuilder();
        try{
            //如果不设置classpath属性的话会导致运行a.class时报找不到类文件的错误,按自己的修改
            Process process = Runtime.getRuntime().exec("cmd /c set CLASSPATH=C:/Users/admin/task_consumer/temp_execute_files/ && java a" + id);

            //这里可能需要修改编码GB2312、GBK、UTF-8
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
            writer.write(input);
            writer.close();

            boolean isTimeLimitNoExceeded = process.waitFor(1, TimeUnit.SECONDS);

            if(!isTimeLimitNoExceeded){
                process.destroy();
                return "Time Limit Exceeded";
            }

            BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            //获得错误信息
            String errorMessage = errorReader.readLine();
            errorReader.close();
            if (errorMessage != null) {
                process.destroy();
                return "Runtime Error";
            }

            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            //获得执行结果,即执行文件System.out的内容
            while ((line = reader.readLine()) != null) {
                result.append(line + '\n');
            }
            reader.close();
            process.destroy();
        }catch(Exception e) {
            e.printStackTrace();
            return "Runtime Error";
        }
        return result.toString();
    }
}


获得的结果,与正确值对比,正确报Accept,错误报Wrong Answer。如果想使用更详细的执行错误的信息,可以使用Process.getErrorStream()获得Error流信息。
关于process类的使用,这篇文章写的非常详细[https://zhuanlan.zhihu.com/p/44957705]

一些文件相关的函数

package handler;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

public class FileHandler {
    public static String dirPath = "temp_execute_files";

    public static void makeFile(String id, String content){
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File sourceFile = new File(idToFilePath(id));
        try {
            if(!sourceFile.exists()){
                sourceFile.createNewFile();
            }
            Files.write(sourceFile.toPath(), content.getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String idToFilePath(String id){
        return dirPath + "/a"+ id + ".java";
    }

    public static String idToSourceFilePath(String id){
        return dirPath + "/a" + id;
    }

    public static boolean isClassFileExists(String id){
        File file = new File(dirPath + "/a"+ id + ".class");
        return file.exists();
    }
}

2.使用反射

反射也可以实现上面的流程,反射可以执行一个文件并且返回它的结果。如果只是想完成Java的编译和执行,Java自带反射,实现比runtime.exec方法简单。但是TLE的判断需要自己做。

代码示例:

package util;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;

public class CompileFileHandler{
    public boolean compileJava(String filePath) {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        if (compiler == null) {
            return false;
        }

        int compilationResult = compiler.run(null, null, null, filePath);
        if (compilationResult != 0) {
            return false;
        }
        return true;
    }
}

package util;

import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

public class ExecuteFileHandler {
    public String executeJava(URL url, String filePath, String input) {
        try {
            URLClassLoader classLoader = URLClassLoader.newInstance(new URL[]{url});
            Class<?> cls = Class.forName(filePath, true, classLoader);
            Object instance = cls.newInstance();
            Method method = cls.getDeclaredMethod("solution", String.class);
            String result = (String) method.invoke(instance, input);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return "Runtime Error";
        }
    }
}

3.计时

反射的计时需要自己做,但是runtime.exec方法则不需要,注意到Process.waitFor的另一个方法waitFor(long timeout, TimeUnit unit)的源码:

public boolean waitFor(long timeout, TimeUnit unit)
    throws InterruptedException
{
    long startTime = System.nanoTime();
    long rem = unit.toNanos(timeout);

    do {
        try {
            exitValue();
            return true;
        } catch(IllegalThreadStateException ex) {
            if (rem > 0)
                Thread.sleep(
                    Math.min(TimeUnit.NANOSECONDS.toMillis(rem) + 1, 100));
        }
        rem = unit.toNanos(timeout) - (System.nanoTime() - startTime);
    } while (rem > 0);
    return false;
}

大概这个意思就是,看看执行完了没有,执行完了就返回true,没执行完会过min(timeout, 100毫秒)的时间会再来看看,要是timeout过了还没执行完,那就返回false。

写的非常好,这样写计时线程,精度会更高,很多地方都可以用到这种思想(要是我来写直接sleep(1000))。所以在我们的ExecuteFileHandler 中有以下判断:


boolean isTimeLimitNoExceeded = process.waitFor(1, TimeUnit.SECONDS);

if(!isTimeLimitNoExceeded){
    process.destroy();
    return "Time Limit Exceeded";
}

注意这里waitFor是不会去处理线程的状态,只是对于状态的一种判断。所以记得要destroy线程。

测试

我建议拿这个题目做测试,上楼梯(斐波那契数列)

楼梯有n阶台阶,上楼可以一步上1阶,也可以一步上2阶,走完n阶台阶共有多少种不同的走法?
实际上,这是一个斐波那契数列,f(n) = f(n-1) + f(n-2)
f(0) = 1、f(1) = 1、f(2) = 2、f(3) = 3、 f(4) = 5、f(5) = 8、f(6) = 13、f(7) = 21、f(8) = 34…
解法:
1.递归
时间复杂度O(2 ^ N),空间复杂度O(2 ^ N)
2.动态规划
时间复杂度O(N),空间复杂度O(N)可降至O(1)
3.快速幂
时间复杂度O(logN) 空间复杂度O(1)

这里的目标是递归不给通过(报Time Limit Exceeded),动态规划和快速幂可以通过。


总结

简单地完成了我们的判题端

  • 5
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值