Blog

Java8 で5番目の問題を解く件

Java には eval がないから実装が面倒だ。そんな風に考えていた時期が私にもありました。

最近の Java 8 には JavaScript engine である Nashorn が標準搭載されているので、これを利用すればよろしい。

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

public class Fifth {
    private static final String[] OPS = new String [] { "+", "-", "" };
    private final ScriptEngine engine;

    public Fifth() {
        ScriptEngineManager manager = new ScriptEngineManager();
        this.engine = manager.getEngineByName("js");
    }

    private void doMain() throws ScriptException {
        calc("1", 1);
    }

    private void calc(String b, long n) throws ScriptException {
        if (n==9) {
            if (eval(b) == 100) {
                System.out.println(b);
            }
        } else {
            for (String op: OPS) {
                calc(b + op + (n+1), n+1);
            }
        }
    }

    public int eval(String code) throws ScriptException {
        Object result = this.engine.eval(code);
        if (result instanceof Double) {
            return (int)((double)result);
        } else {
            return (Integer) result;
        }
    }

    public static void main(String [] args) throws ScriptException {
        new Fifth().doMain();
    }

}