Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

576
LINES

< > BotCompany Repo | #685 // IOIOI Processor (v4, multi-case)

JavaX source code - run with: x30.jar

!636
!quickmain
!auto-import
!standard functions
!quicknew
!1000346 // use "case" as a variable name
!688 // buf.isEmpty
!class JavaTok

import java.lang.reflect.*;

interface Learner {
  public void processInOut(String in, String out);
  public String processIn(String in);
  public void toJava(Code code);
}

interface Function {
  public Object process(Object in);
  public void toJava_process(Code code);
}

interface ReversibleFunction extends Function {
  public Object unprocess(Object in);
  public void toJava_unprocess(Code code);
}

// generic learner (works on objects)
interface GLearner {
  public void processInOut(Object in, Object out);
  public Object processIn(Object in);
  public void toJava(Code code);
}

abstract class Base {
  void printVars() {
    new StringBuilder buf;
    Field[] fields = getClass().getDeclaredFields();
    for (Field field : fields) {
      if ((field.getModifiers() & Modifier.STATIC) != 0)
        continue;
      Object value;
      try {
        value = field.get(this);
      } catch (Exception e) {
        value = "?";
      }
      
      if (!buf.isEmpty()) buf.append(", ");
      buf.append(field.getName() + "=" + value);
    }
    System.out.println(buf.toString());
  }
}

abstract class LearnerImpl extends Base implements Learner {
}

abstract class GLearnerImpl extends Base implements GLearner {
}

class WrappedGLearner extends LearnerImpl {
  GLearner learner;
  
  WrappedGLearner(GLearner learner) {
    this.learner = learner;
  }
  
  public void processInOut(String in, String out) {
    learner.processInOut(in, out);
  }
  
  public String processIn(String in) {
    return (String) learner.processIn(in);
  }
  
  public void toJava(Code code) {
    learner.toJava(code);
  }
}

class Code {
  StringBuilder buf = new StringBuilder();
  String var = "in";
  String indent = "";
  
  void line(String line) {
    buf.append(indent).append(line).append('\n');
  }
  
  void indent() {
    indent += "  ";
  }
  
  void unindent() {
    indent = indent.substring(0, indent.length()-2);
  }
}

main {
  static List<Case> cases = new ArrayList<Case>();
  
  psvm {
    String snippetID = null;
    
    for (int i = 0; i < args.length; i++) {
      String arg = args[i];
      if (arg.equals("debug"))
        debugOn(args[++i]);
      else if (isSnippetID(arg))
        snippetID = arg;
      else
        System.err.println("Unknown argument: " + arg + ", ignoring");
    }
    
    parse(snippetID);
    
    int solved = 0, n = cases.size();
    for (int i = 0; i < n; i++) {
      calculate(cases.get(i));
      if (cases.get(i).winner != null)
        ++solved;
      System.out.println((i+1) + " case(s) processed, " + solved + " solved.");
    }

    print ""    
    print "----"

    boolean allSolved = solved == n;
    if (!allSolved) {
      System.out.println();
      System.out.print("Unsolved: ");
      for (Case case : cases)
        if (case.winner == null)
          System.out.print(case.id + " ");
      System.out.println();
    }
    if (solved != 0) {
      System.out.println();
      System.out.print("Solved: ");
      for (Case case : cases)
        if (case.winner != null)
          System.out.print(case.id + " ");
      System.out.println();
    }
    System.out.println();
    System.out.println(allSolved ? "ALL SOLVED (" + solved + ")" : "Solved " + solved + " out of " + n + ".");
    print ""
  }
  
  static class Case {
    String id;
    List<String[]> fullExamples = new ArrayList<String[]>();
    List<String> halfExamples = new ArrayList<String>();
    List<String[]> examples1, examples2;
    Learner winner;
  }

  static void parse(String arg) tex {
    Case case = new Case();
    String text;
    if (arg != null) {
      case.id = arg;
      text = loadSnippet(arg);
    } else {
      case.id = "input.txt";
      text = loadTextFile("input/input.txt", null);
      if (text == null) {
        //case.id = "#2000455";  // example input
        case.id = "#681"; // a collection of "all cases"!
        text = loadSnippet(case.id);
      }
    }
    
    // it's a collection of cases!
    if (text.trim().startsWith("#")) {
      for (String line : toLines(text))
        parse(line);
      return;
    }
      
    System.out.println(text);
    String in = null, out = null;
    
    for (String line : toLines(text)) {
      if (line.startsWith("I")) { // "In: " or "I: "
        if (in != null)
          case.halfExamples.add(in);
        in = unquote(line.substring(line.indexOf(':')+1).trim());
        out = null;
      } else if (line.startsWith("O")) { // "Out: " or "O: "
        out = unquote(line.substring(line.indexOf(':')+1).trim());
        System.out.println(quote(in) + " => " + quote(out));
        case.fullExamples.add(new String[] {in, out});
        in = out = null;
      }
    }
    
    if (in != null)
      case.halfExamples.add(in);
    cases.add(case);
  }
  
  static void calculate(Case case) tex {
    if (case.fullExamples.size() < 2)
      throw new RuntimeException("Too few examples (" + case.fullExamples.size() + ")");
    int splitPoint = case.fullExamples.size()-1;
    System.out.println("Full examples: " + case.fullExamples.size() + ", splitPoint: " + splitPoint);
    case.examples1 = case.fullExamples.subList(0, splitPoint);
    case.examples2 = case.fullExamples.subList(splitPoint, case.fullExamples.size());
    
    Learner learner = findOKLearner(case);
    if (learner == null)
      print "\nProblem not solved"
    else {
      print "\nSolved!\n"
      case.winner = learner;
      Code code = new Code();
      learner.toJava(code);
      System.out.println("Java:");
      System.out.println(indent("  ", code.buf.toString()));
      for (String in : case.halfExamples) {
        String out = learner.processIn(in);
        System.out.println(quote(in) + " =>! " + quote(out));
      }
    }
  }
  
  static Learner findOKLearner(Case case) {
    for (Learner learner : makeLearners()) try {
      if (learnerOK(learner, case))
        return learner;
    } catch (Throwable e) {
      e.printStackTrace();
    }
    return null;
  }
  
  static boolean learnerOK(Learner learner, Case case) {
    String[] _e = null;
    try {
      for (String[] e : case.examples1) {
        _e = e;
        learner.processInOut(e[0], e[1]);
      }
      
      // full validation against all examples
      for (String[] e : case.fullExamples) {
        _e = e;
        String out = learner.processIn(e[0]);
        if (!e[1].equals(out)) {
          System.out.println("[fail] " + learner + " on " + quote(e[0]) + " - got: " + quote(out) + " rather than: " + quote(e[1]));
          return false;
        }
      }
      return true; // all test examples passed
    } catch (Throwable e) {
        System.out.println("[fail] " + learner + " on " + (_e == null ? "?" : quote(_e[0])) + " - " + e);
      silentException(e);
      return false;
    }
  }
  
  static void silentException(Throwable e) {
  }
  
  static Iterable<Learner> makeLearners() {
    List<Learner> list = new ArrayList<Learner>();
    //list.add(new LId()); // subsumed by trivial case of PrefixSuffix
    list.add(new LPrefixSuffix());
    list.add(new LSplitInput(new LOutPattern()));
    list.add(new LInputPattern());
    list.add(wrap(new LFixed()));
    list.add(wrap(new LBoth(new RFJavaTok(), new LEach(new LFixedFunction(new EscapeCase())))));
    return list;
  }
  
  public static String unquote(String s) {
    if (s.startsWith("\"") && s.endsWith("\"") && s.length() > 1)
      return s.substring(1, s.length()-1).replace("\\\"", "\"").replace("\\\\", "\\"); // SHOULD work...
    else
      return s; // Return SOMETHING
  }
  
  public static String quote(String s) {
    if (s == null) return "null";
    return "\"" + s.replace("\\", "\\\\").replace("\"", "\\\"") + "\"";
  }
  
  static String indent(String indent, String s) {
    return indent + s.replace("\n", "\n" + indent);
  }
  
  static void debugOn(String name) {
    try {
      Class c = Class.forName("main$" + name);
      Field field;
      while (true)
        try {
          field = c.getDeclaredField("debug");
          break;
        } catch  (NoSuchFieldException e) {
          c = c.getSuperclass();
        }
      field.setBoolean(null, true);
    } catch (Exception e) {
      e.printStackTrace();
      System.err.println("Cannot debug class " + name);
    }
  }
  
  static Learner wrap(GLearner learner) {
    return new WrappedGLearner(learner);
  }
  
  // splits the input at some point, takes only one part
  static class LSplitInput implements Learner {
    int splitIdx = 1; // split after first character
    Learner baseLearner;
    
    LSplitInput(Learner baseLearner) {
      this.baseLearner = baseLearner;
    }
    
    public void processInOut(String in, String out) {
      in = in.substring(splitIdx);
      baseLearner.processInOut(in, out);
    }
    
    public String processIn(String in) {
      in = in.substring(splitIdx);
      return baseLearner.processIn(in);
    }
    
    public void toJava(Code code) {
      code.line(code.var + " = ((String) " + code.var + ").substring(" + splitIdx + ");");
      baseLearner.toJava(code);
    }
  }
  
  // if input appears in output in fixed pattern
  static class LOutPattern implements Learner {
    String pattern = "%!%";

    public void processInOut(String in, String out) {
      pattern = out.replace(in, "%!%");
    }
    
    public String processIn(String in) {
      return pattern.replace("%!%", in);
    }
    
    public void toJava(Code code) {
      code.line(code.var + " = " + quote(pattern) + ".replace(" + quote("%!%") + ", (String) " + code.var + ");");
    }
  }
  
  // learns to exchange common prefixes and suffixes
  static class LPrefixSuffix extends LearnerImpl {
    static boolean debug;
    String prefixIn, suffixIn, prefixOut, suffixOut;
    
    public void processInOut(String in, String out) {
      updateIn(in);
      prefixOut = prefixOut == null ? out : commonPrefix(prefixOut, out);
      suffixOut = suffixOut == null ? out : commonSuffix(suffixOut, out);
      if (debug)
        printState("processInOut(" + quote(in) + ", " + quote(out) + ")");
    }
    
    void updateIn(String in) {
      prefixIn = prefixIn == null ? in : commonPrefix(prefixIn, in);
      suffixIn = suffixIn == null ? in : commonSuffix(suffixIn, in);
      if (debug)
        printState("updateIn(" + quote(in) + ")");
    }

    public String processIn(String in) {
      //System.out.println("[before last info] " + quote(prefixIn) + " " + quote(suffixIn) + " " + quote(prefixOut) + " " + quote(suffixOut));
      //System.out.println("[last info] " + quote(in));
      
      // use latest information
      String p = prefixIn, s = suffixIn;
      updateIn(in);
      prefixOut = prefixOut.substring(0, prefixOut.length()-(p.length()-prefixIn.length()));
      suffixOut = suffixOut.substring(s.length()-suffixIn.length());
      
      //System.out.println("[after last info] " + quote(prefixIn) + " " + quote(suffixIn) + " " + quote(prefixOut) + " " + quote(suffixOut));
      String core = in.substring(prefixIn.length(), in.length()-suffixIn.length());
      return prefixOut + core + suffixOut;
    }
    
    public void toJava(Code code) {
      code.line(code.var + " = ((String) " + code.var + ").substring(" + prefixIn.length() + ", in.length()-" + suffixIn.length() + ");");
      code.line(code.var + " = " + quote(prefixOut) + " + " + code.var + " + " + quote(suffixOut) + ";");
    }
    
    void printState(String text) {
      System.out.println(text);
      printVars();
    }
  }
  
  // for "find" tasks (e.g. "abcde" to "[[abc]]de")
  static class LInputPattern implements Learner {
    String regexp = "";
    
    public void processInOut(String in, String out) {
      int i = out.indexOf("[["), j = out.indexOf("]]", i+1);
      if (j < 0) return;
      String s = out.substring(i+2, j);
      regexp = s.replaceAll("\\d+", Matcher.quoteReplacement("\\d+"));
      System.out.println("regexp: " + regexp);
    }
    
    public String processIn(String in) {
      if (regexp.length() == 0)
        return in;
      else
        return in.replaceAll("(" + regexp + ")", "[[$1]]");
    }
    
    public void toJava(Code code) {
      code.line(code.var + " = ((String) " + code.var + ").replaceAll(" + quote("(" + regexp + ")") + ", \"[[$1]]\");");
    }
  }
  
  static class LFixed extends GLearnerImpl {
    static boolean debug;
    Object value;
    
    public void processInOut(Object in, Object out) {
      value = out;
      if (debug)
        printVars();
    }
    
    public Object processIn(Object in) {
      return value;
    }
    
    public void toJava(Code code) {
      code.line(code.var + " = " + quote((String) value) + ";");
    }
  }
  
  static void fail(String msg) {
    throw new RuntimeException(msg);
  }
  
  static void assertSameSize(List a, List b) {
    if (a.size() != b.size())
      fail("wrong list sizes");
  }

  // process lists in parallel
  // (in and out must be a list of same length)
  static class LEach extends GLearnerImpl {
    static boolean debug;
    GLearner base;
    
    LEach(GLearner base) {
      this.base = base;
    }
    
    public void processInOut(Object _in, Object _out) {
      List in = (List) _in, out = (List) _out;
      assertSameSize(in, out);
      for (int i = 0; i < in.size(); i++)
        base.processInOut(in.get(i), out.get(i));
      if (debug)
        printVars();
    }
    
    public Object processIn(Object _in) {
      List in = (List) _in;
      List out = new ArrayList();
      for (Object x : in)
        out.add(base.processIn(x));
      return out;
    }
    
    public void toJava(Code code) {
      code.line("List out = new ArrayList();");
      code.line("for (Object x : (List) in) {");
      code.indent();
      code.line("in = x;");
      base.toJava(code);
      code.line("out.add(in);");
      code.unindent();
      code.line("}");
      code.line("in = out;");
    }
  }
  
  static class LBoth extends GLearnerImpl {
    ReversibleFunction f;
    GLearner base;
    
    LBoth(ReversibleFunction f, GLearner base) {
      this.f = f;
      this.base = base;
    }
    
    public void processInOut(Object in, Object out) {
      in = f.process(in);
      out = f.process(out);
      base.processInOut(in, out);
    }
    
    public Object processIn(Object in) {
      in = f.process(in);
      in = base.processIn(in);
      in = f.unprocess(in);
      return in;
    }
    
    public void toJava(Code code) {
      f.toJava_process(code);
      base.toJava(code);
      f.toJava_unprocess(code);
    }
  }
  
  static class RFJavaTok implements ReversibleFunction {
    public Object process(Object in) {
      return JavaTok.split((String) in);
    }
    
    public Object unprocess(Object in) {
      return JavaTok.join((List) in);
    }
    
    public void toJava_process(Code code) {
      code.line(code.var + " = JavaTok.split((String) " + code.var + ");");
    }
    
    public void toJava_unprocess(Code code) {
      code.line(code.var + " = JavaTok.join((List) " + code.var + ");");
    }
  }
  
  static class LFixedFunction extends GLearnerImpl {
    Function f;
    
    LFixedFunction(Function f) {
      this.f = f;
    }
    
    public void processInOut(Object in, Object out) {
    }
    
    public Object processIn(Object in) {
      return f.process(in);
    }
    
    public void toJava(Code code) {
      f.toJava_process(code);
    }
  }
  
  static class EscapeCase implements Function {
    static boolean debug;
    
    public Object process(Object _in) {
      if (debug)
        System.out.println("EscapeCase: " + _in);
      String in = (String) _in;
      return in.equals("case") ? "_case" : in;
    }
    
    public void toJava_process(Code code) {
      code.line("if (\"case\".equals(" + code.var + ")) " + code.var + " = " + quote("_case") + ";");
    }
  }
}

Author comment

Began life as a copy of #678

download  show line numbers  debug dex  old transpilations   

Travelled to 14 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, teubizvjbppd, tslmcundralx, tvejysmllsmz, vouqrxazstgt

Comments [hide]

ID Author/Program Comment Date
610 #1000610 (pitcher) 2015-08-18 00:07:07
609 #1000604 (pitcher) 2015-08-20 15:28:24

add comment

Snippet ID: #685
Snippet name: IOIOI Processor (v4, multi-case)
Eternal ID of this version: #685/1
Text MD5: 73ec7288ba1748f89a7cf4ea7ce62a30
Author: stefan
Category:
Type: JavaX source code
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2015-07-27 19:48:42
Source code size: 16554 bytes / 576 lines
Pitched / IR pitched: No / Yes
Views / Downloads: 1462 / 1133
Referenced in: [show references]