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

608
LINES

< > BotCompany Repo | #690 // IOIOI Processor (v6, with char shift)

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

Author comment

Began life as a copy of #689

download  show line numbers  debug dex  old transpilations   

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

No comments. add comment

Snippet ID: #690
Snippet name: IOIOI Processor (v6, with char shift)
Eternal ID of this version: #690/1
Text MD5: 49963becf59d0b40dda655609c26e097
Author: stefan
Category:
Type: JavaX source code
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2015-07-29 19:21:05
Source code size: 18221 bytes / 608 lines
Pitched / IR pitched: No / Yes
Views / Downloads: 640 / 565
Referenced in: [show references]