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

1  
!636
2  
!quickmain
3  
!auto-import
4  
!standard functions
5  
!quicknew
6  
!1000346 // use "case" as a variable name
7  
!688 // buf.isEmpty
8  
!class JavaTok
9  
10  
import java.lang.reflect.*;
11  
12  
interface Learner {
13  
  public void processInOut(String in, String out);
14  
  public String processIn(String in);
15  
  public void toJava(Code code);
16  
}
17  
18  
interface Function {
19  
  public Object process(Object in);
20  
  public void toJava_process(Code code);
21  
}
22  
23  
interface ReversibleFunction extends Function {
24  
  public Object unprocess(Object in);
25  
  public void toJava_unprocess(Code code);
26  
}
27  
28  
// generic learner (works on objects)
29  
interface GLearner {
30  
  public void processInOut(Object in, Object out);
31  
  public Object processIn(Object in);
32  
  public void toJava(Code code);
33  
}
34  
35  
abstract class Base {
36  
  void printVars() {
37  
    new StringBuilder buf;
38  
    Field[] fields = getClass().getDeclaredFields();
39  
    for (Field field : fields) {
40  
      if ((field.getModifiers() & Modifier.STATIC) != 0)
41  
        continue;
42  
      Object value;
43  
      try {
44  
        value = field.get(this);
45  
      } catch (Exception e) {
46  
        value = "?";
47  
      }
48  
      
49  
      if (!buf.isEmpty()) buf.append(", ");
50  
      buf.append(field.getName() + "=" + value);
51  
    }
52  
    System.out.println(buf.toString());
53  
  }
54  
}
55  
56  
abstract class LearnerImpl extends Base implements Learner {
57  
}
58  
59  
abstract class GLearnerImpl extends Base implements GLearner {
60  
}
61  
62  
class WrappedGLearner extends LearnerImpl {
63  
  GLearner learner;
64  
  
65  
  WrappedGLearner(GLearner learner) {
66  
    this.learner = learner;
67  
  }
68  
  
69  
  public void processInOut(String in, String out) {
70  
    learner.processInOut(in, out);
71  
  }
72  
  
73  
  public String processIn(String in) {
74  
    return (String) learner.processIn(in);
75  
  }
76  
  
77  
  public void toJava(Code code) {
78  
    learner.toJava(code);
79  
  }
80  
}
81  
82  
class Code {
83  
  StringBuilder buf = new StringBuilder();
84  
  String var = "in";
85  
  String indent = "";
86  
  
87  
  void line(String line) {
88  
    buf.append(indent).append(line).append('\n');
89  
  }
90  
  
91  
  void indent() {
92  
    indent += "  ";
93  
  }
94  
  
95  
  void unindent() {
96  
    indent = indent.substring(0, indent.length()-2);
97  
  }
98  
}
99  
100  
main {
101  
  static List<Case> cases = new ArrayList<Case>();
102  
  
103  
  psvm {
104  
    String snippetID = null;
105  
    
106  
    for (int i = 0; i < args.length; i++) {
107  
      String arg = args[i];
108  
      if (arg.equals("debug"))
109  
        debugOn(args[++i]);
110  
      else if (isSnippetID(arg))
111  
        snippetID = arg;
112  
      else
113  
        System.err.println("Unknown argument: " + arg + ", ignoring");
114  
    }
115  
    
116  
    parse(snippetID);
117  
    
118  
    int solved = 0, n = cases.size();
119  
    for (int i = 0; i < n; i++) {
120  
      calculate(cases.get(i));
121  
      if (cases.get(i).winner != null)
122  
        ++solved;
123  
      System.out.println((i+1) + " case(s) processed, " + solved + " solved.");
124  
    }
125  
126  
    print ""    
127  
    print "----"
128  
129  
    boolean allSolved = solved == n;
130  
    if (!allSolved) {
131  
      System.out.println();
132  
      System.out.print("Unsolved: ");
133  
      for (Case case : cases)
134  
        if (case.winner == null)
135  
          System.out.print(case.id + " ");
136  
      System.out.println();
137  
    }
138  
    if (solved != 0) {
139  
      System.out.println();
140  
      System.out.print("Solved: ");
141  
      for (Case case : cases)
142  
        if (case.winner != null)
143  
          System.out.print(case.id + " ");
144  
      System.out.println();
145  
    }
146  
    System.out.println();
147  
    System.out.println(allSolved ? "ALL SOLVED (" + solved + ")" : "Solved " + solved + " out of " + n + ".");
148  
    print ""
149  
  }
150  
  
151  
  static class Case {
152  
    String id;
153  
    List<String[]> fullExamples = new ArrayList<String[]>();
154  
    List<String> halfExamples = new ArrayList<String>();
155  
    List<String[]> examples1, examples2;
156  
    Learner winner;
157  
  }
158  
159  
  static void parse(String arg) tex {
160  
    Case case = new Case();
161  
    String text;
162  
    if (arg != null) {
163  
      case.id = arg;
164  
      text = loadSnippet(arg);
165  
    } else {
166  
      case.id = "input.txt";
167  
      text = loadTextFile("input/input.txt", null);
168  
      if (text == null) {
169  
        //case.id = "#2000455";  // example input
170  
        case.id = "#681"; // a collection of "all cases"!
171  
        text = loadSnippet(case.id);
172  
      }
173  
    }
174  
    
175  
    // it's a collection of cases!
176  
    if (text.trim().startsWith("#")) {
177  
      for (String line : toLines(text))
178  
        parse(line);
179  
      return;
180  
    }
181  
      
182  
    System.out.println(text);
183  
    String in = null, out = null;
184  
    
185  
    for (String line : toLines(text)) {
186  
      if (line.startsWith("I")) { // "In: " or "I: "
187  
        if (in != null)
188  
          case.halfExamples.add(in);
189  
        in = unquote(line.substring(line.indexOf(':')+1).trim());
190  
        out = null;
191  
      } else if (line.startsWith("O")) { // "Out: " or "O: "
192  
        out = unquote(line.substring(line.indexOf(':')+1).trim());
193  
        System.out.println(quote(in) + " => " + quote(out));
194  
        case.fullExamples.add(new String[] {in, out});
195  
        in = out = null;
196  
      }
197  
    }
198  
    
199  
    if (in != null)
200  
      case.halfExamples.add(in);
201  
    cases.add(case);
202  
  }
203  
  
204  
  static void calculate(Case case) tex {
205  
    if (case.fullExamples.size() < 2)
206  
      throw new RuntimeException("Too few examples (" + case.fullExamples.size() + ")");
207  
    int splitPoint = case.fullExamples.size()-1;
208  
    System.out.println("Full examples: " + case.fullExamples.size() + ", splitPoint: " + splitPoint);
209  
    case.examples1 = case.fullExamples.subList(0, splitPoint);
210  
    case.examples2 = case.fullExamples.subList(splitPoint, case.fullExamples.size());
211  
    
212  
    Learner learner = findOKLearner(case);
213  
    if (learner == null)
214  
      print "\nProblem not solved"
215  
    else {
216  
      print "\nSolved!\n"
217  
      case.winner = learner;
218  
      Code code = new Code();
219  
      learner.toJava(code);
220  
      System.out.println("Java:");
221  
      System.out.println(indent("  ", code.buf.toString()));
222  
      for (String in : case.halfExamples) {
223  
        String out = learner.processIn(in);
224  
        System.out.println(quote(in) + " =>! " + quote(out));
225  
      }
226  
    }
227  
  }
228  
  
229  
  static Learner findOKLearner(Case case) {
230  
    for (Learner learner : makeLearners()) try {
231  
      if (learnerOK(learner, case))
232  
        return learner;
233  
    } catch (Throwable e) {
234  
      e.printStackTrace();
235  
    }
236  
    return null;
237  
  }
238  
  
239  
  static boolean learnerOK(Learner learner, Case case) {
240  
    String[] _e = null;
241  
    try {
242  
      for (String[] e : case.examples1) {
243  
        _e = e;
244  
        learner.processInOut(e[0], e[1]);
245  
      }
246  
      
247  
      // full validation against all examples
248  
      for (String[] e : case.fullExamples) {
249  
        _e = e;
250  
        String out = learner.processIn(e[0]);
251  
        if (!e[1].equals(out)) {
252  
          System.out.println("[fail] " + learner + " on " + quote(e[0]) + " - got: " + quote(out) + " rather than: " + quote(e[1]));
253  
          return false;
254  
        }
255  
      }
256  
      return true; // all test examples passed
257  
    } catch (Throwable e) {
258  
        System.out.println("[fail] " + learner + " on " + (_e == null ? "?" : quote(_e[0])) + " - " + e);
259  
      silentException(e);
260  
      return false;
261  
    }
262  
  }
263  
  
264  
  static void silentException(Throwable e) {
265  
  }
266  
  
267  
  static Iterable<Learner> makeLearners() {
268  
    List<Learner> list = new ArrayList<Learner>();
269  
    //list.add(new LId()); // subsumed by trivial case of PrefixSuffix
270  
    list.add(new LPrefixSuffix());
271  
    list.add(new LSplitInput(new LOutPattern()));
272  
    list.add(new LInputPattern());
273  
    list.add(wrap(new LFixed()));
274  
    list.add(wrap(new LBoth(new RFJavaTok(), new LEach(new LFixedFunction(new EscapeCase())))));
275  
    return list;
276  
  }
277  
  
278  
  public static String unquote(String s) {
279  
    if (s.startsWith("\"") && s.endsWith("\"") && s.length() > 1)
280  
      return s.substring(1, s.length()-1).replace("\\\"", "\"").replace("\\\\", "\\"); // SHOULD work...
281  
    else
282  
      return s; // Return SOMETHING
283  
  }
284  
  
285  
  public static String quote(String s) {
286  
    if (s == null) return "null";
287  
    return "\"" + s.replace("\\", "\\\\").replace("\"", "\\\"") + "\"";
288  
  }
289  
  
290  
  static String indent(String indent, String s) {
291  
    return indent + s.replace("\n", "\n" + indent);
292  
  }
293  
  
294  
  static void debugOn(String name) {
295  
    try {
296  
      Class c = Class.forName("main$" + name);
297  
      Field field;
298  
      while (true)
299  
        try {
300  
          field = c.getDeclaredField("debug");
301  
          break;
302  
        } catch  (NoSuchFieldException e) {
303  
          c = c.getSuperclass();
304  
        }
305  
      field.setBoolean(null, true);
306  
    } catch (Exception e) {
307  
      e.printStackTrace();
308  
      System.err.println("Cannot debug class " + name);
309  
    }
310  
  }
311  
  
312  
  static Learner wrap(GLearner learner) {
313  
    return new WrappedGLearner(learner);
314  
  }
315  
  
316  
  // splits the input at some point, takes only one part
317  
  static class LSplitInput implements Learner {
318  
    int splitIdx = 1; // split after first character
319  
    Learner baseLearner;
320  
    
321  
    LSplitInput(Learner baseLearner) {
322  
      this.baseLearner = baseLearner;
323  
    }
324  
    
325  
    public void processInOut(String in, String out) {
326  
      in = in.substring(splitIdx);
327  
      baseLearner.processInOut(in, out);
328  
    }
329  
    
330  
    public String processIn(String in) {
331  
      in = in.substring(splitIdx);
332  
      return baseLearner.processIn(in);
333  
    }
334  
    
335  
    public void toJava(Code code) {
336  
      code.line(code.var + " = ((String) " + code.var + ").substring(" + splitIdx + ");");
337  
      baseLearner.toJava(code);
338  
    }
339  
  }
340  
  
341  
  // if input appears in output in fixed pattern
342  
  static class LOutPattern implements Learner {
343  
    String pattern = "%!%";
344  
345  
    public void processInOut(String in, String out) {
346  
      pattern = out.replace(in, "%!%");
347  
    }
348  
    
349  
    public String processIn(String in) {
350  
      return pattern.replace("%!%", in);
351  
    }
352  
    
353  
    public void toJava(Code code) {
354  
      code.line(code.var + " = " + quote(pattern) + ".replace(" + quote("%!%") + ", (String) " + code.var + ");");
355  
    }
356  
  }
357  
  
358  
  // learns to exchange common prefixes and suffixes
359  
  static class LPrefixSuffix extends LearnerImpl {
360  
    static boolean debug;
361  
    String prefixIn, suffixIn, prefixOut, suffixOut;
362  
    
363  
    public void processInOut(String in, String out) {
364  
      updateIn(in);
365  
      prefixOut = prefixOut == null ? out : commonPrefix(prefixOut, out);
366  
      suffixOut = suffixOut == null ? out : commonSuffix(suffixOut, out);
367  
      if (debug)
368  
        printState("processInOut(" + quote(in) + ", " + quote(out) + ")");
369  
    }
370  
    
371  
    void updateIn(String in) {
372  
      prefixIn = prefixIn == null ? in : commonPrefix(prefixIn, in);
373  
      suffixIn = suffixIn == null ? in : commonSuffix(suffixIn, in);
374  
      if (debug)
375  
        printState("updateIn(" + quote(in) + ")");
376  
    }
377  
378  
    public String processIn(String in) {
379  
      //System.out.println("[before last info] " + quote(prefixIn) + " " + quote(suffixIn) + " " + quote(prefixOut) + " " + quote(suffixOut));
380  
      //System.out.println("[last info] " + quote(in));
381  
      
382  
      // use latest information
383  
      String p = prefixIn, s = suffixIn;
384  
      updateIn(in);
385  
      prefixOut = prefixOut.substring(0, prefixOut.length()-(p.length()-prefixIn.length()));
386  
      suffixOut = suffixOut.substring(s.length()-suffixIn.length());
387  
      
388  
      //System.out.println("[after last info] " + quote(prefixIn) + " " + quote(suffixIn) + " " + quote(prefixOut) + " " + quote(suffixOut));
389  
      String core = in.substring(prefixIn.length(), in.length()-suffixIn.length());
390  
      return prefixOut + core + suffixOut;
391  
    }
392  
    
393  
    public void toJava(Code code) {
394  
      code.line(code.var + " = ((String) " + code.var + ").substring(" + prefixIn.length() + ", in.length()-" + suffixIn.length() + ");");
395  
      code.line(code.var + " = " + quote(prefixOut) + " + " + code.var + " + " + quote(suffixOut) + ";");
396  
    }
397  
    
398  
    void printState(String text) {
399  
      System.out.println(text);
400  
      printVars();
401  
    }
402  
  }
403  
  
404  
  // for "find" tasks (e.g. "abcde" to "[[abc]]de")
405  
  static class LInputPattern implements Learner {
406  
    String regexp = "";
407  
    
408  
    public void processInOut(String in, String out) {
409  
      int i = out.indexOf("[["), j = out.indexOf("]]", i+1);
410  
      if (j < 0) return;
411  
      String s = out.substring(i+2, j);
412  
      regexp = s.replaceAll("\\d+", Matcher.quoteReplacement("\\d+"));
413  
      System.out.println("regexp: " + regexp);
414  
    }
415  
    
416  
    public String processIn(String in) {
417  
      if (regexp.length() == 0)
418  
        return in;
419  
      else
420  
        return in.replaceAll("(" + regexp + ")", "[[$1]]");
421  
    }
422  
    
423  
    public void toJava(Code code) {
424  
      code.line(code.var + " = ((String) " + code.var + ").replaceAll(" + quote("(" + regexp + ")") + ", \"[[$1]]\");");
425  
    }
426  
  }
427  
  
428  
  static class LFixed extends GLearnerImpl {
429  
    static boolean debug;
430  
    Object value;
431  
    
432  
    public void processInOut(Object in, Object out) {
433  
      value = out;
434  
      if (debug)
435  
        printVars();
436  
    }
437  
    
438  
    public Object processIn(Object in) {
439  
      return value;
440  
    }
441  
    
442  
    public void toJava(Code code) {
443  
      code.line(code.var + " = " + quote((String) value) + ";");
444  
    }
445  
  }
446  
  
447  
  static void fail(String msg) {
448  
    throw new RuntimeException(msg);
449  
  }
450  
  
451  
  static void assertSameSize(List a, List b) {
452  
    if (a.size() != b.size())
453  
      fail("wrong list sizes");
454  
  }
455  
456  
  // process lists in parallel
457  
  // (in and out must be a list of same length)
458  
  static class LEach extends GLearnerImpl {
459  
    static boolean debug;
460  
    GLearner base;
461  
    
462  
    LEach(GLearner base) {
463  
      this.base = base;
464  
    }
465  
    
466  
    public void processInOut(Object _in, Object _out) {
467  
      List in = (List) _in, out = (List) _out;
468  
      assertSameSize(in, out);
469  
      for (int i = 0; i < in.size(); i++)
470  
        base.processInOut(in.get(i), out.get(i));
471  
      if (debug)
472  
        printVars();
473  
    }
474  
    
475  
    public Object processIn(Object _in) {
476  
      List in = (List) _in;
477  
      List out = new ArrayList();
478  
      for (Object x : in)
479  
        out.add(base.processIn(x));
480  
      return out;
481  
    }
482  
    
483  
    public void toJava(Code code) {
484  
      code.line("List out = new ArrayList();");
485  
      code.line("for (Object x : (List) in) {");
486  
      code.indent();
487  
      code.line("in = x;");
488  
      base.toJava(code);
489  
      code.line("out.add(in);");
490  
      code.unindent();
491  
      code.line("}");
492  
      code.line("in = out;");
493  
    }
494  
  }
495  
  
496  
  static class LBoth extends GLearnerImpl {
497  
    ReversibleFunction f;
498  
    GLearner base;
499  
    
500  
    LBoth(ReversibleFunction f, GLearner base) {
501  
      this.f = f;
502  
      this.base = base;
503  
    }
504  
    
505  
    public void processInOut(Object in, Object out) {
506  
      in = f.process(in);
507  
      out = f.process(out);
508  
      base.processInOut(in, out);
509  
    }
510  
    
511  
    public Object processIn(Object in) {
512  
      in = f.process(in);
513  
      in = base.processIn(in);
514  
      in = f.unprocess(in);
515  
      return in;
516  
    }
517  
    
518  
    public void toJava(Code code) {
519  
      f.toJava_process(code);
520  
      base.toJava(code);
521  
      f.toJava_unprocess(code);
522  
    }
523  
  }
524  
  
525  
  static class RFJavaTok implements ReversibleFunction {
526  
    public Object process(Object in) {
527  
      return JavaTok.split((String) in);
528  
    }
529  
    
530  
    public Object unprocess(Object in) {
531  
      return JavaTok.join((List) in);
532  
    }
533  
    
534  
    public void toJava_process(Code code) {
535  
      code.line(code.var + " = JavaTok.split((String) " + code.var + ");");
536  
    }
537  
    
538  
    public void toJava_unprocess(Code code) {
539  
      code.line(code.var + " = JavaTok.join((List) " + code.var + ");");
540  
    }
541  
  }
542  
  
543  
  static class LFixedFunction extends GLearnerImpl {
544  
    Function f;
545  
    
546  
    LFixedFunction(Function f) {
547  
      this.f = f;
548  
    }
549  
    
550  
    public void processInOut(Object in, Object out) {
551  
    }
552  
    
553  
    public Object processIn(Object in) {
554  
      return f.process(in);
555  
    }
556  
    
557  
    public void toJava(Code code) {
558  
      f.toJava_process(code);
559  
    }
560  
  }
561  
  
562  
  static class EscapeCase implements Function {
563  
    static boolean debug;
564  
    
565  
    public Object process(Object _in) {
566  
      if (debug)
567  
        System.out.println("EscapeCase: " + _in);
568  
      String in = (String) _in;
569  
      return in.equals("case") ? "_case" : in;
570  
    }
571  
    
572  
    public void toJava_process(Code code) {
573  
      code.line("if (\"case\".equals(" + code.var + ")) " + code.var + " = " + quote("_case") + ";");
574  
    }
575  
  }
576  
}

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: 1364 / 1032
Referenced in: [show references]