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

1225
LINES

< > BotCompany Repo | #693 // IOIOI Processor (v8, developing)

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  
import java.math.*; // BigInteger
12  
13  
!include #2000470 // class _x16
14  
15  
interface Function {
16  
  public Object process(Object in);
17  
  public void toJava_process(Code code);
18  
}
19  
20  
interface ReversibleFunction extends Function {
21  
  public Object unprocess(Object in);
22  
  public void toJava_unprocess(Code code);
23  
}
24  
25  
// generic learner (works on objects)
26  
interface Learner {
27  
  public void processInOut(Object in, Object out);
28  
  public Object processIn(Object in);
29  
  public void toJava(Code code);
30  
}
31  
32  
abstract class Base {
33  
  void printVars() {
34  
    new StringBuilder buf;
35  
    Field[] fields = getClass().getDeclaredFields();
36  
    for (Field field : fields) {
37  
      if ((field.getModifiers() & Modifier.STATIC) != 0)
38  
        continue;
39  
      Object value;
40  
      try {
41  
        value = field.get(this);
42  
      } catch (Exception e) {
43  
        value = "?";
44  
      }
45  
      
46  
      if (!buf.isEmpty()) buf.append(", ");
47  
      buf.append(field.getName() + "=" + value);
48  
    }
49  
    System.out.println(buf.toString());
50  
  }
51  
}
52  
53  
abstract class LearnerImpl extends Base implements Learner {
54  
}
55  
56  
class Code {
57  
  new StringBuilder buf;
58  
  String var = "in";
59  
  String indent = "";
60  
  new List<String> translators;
61  
  
62  
  Code() {
63  
    translators.add("!636");
64  
  }
65  
  
66  
  void line(String line) {
67  
    buf.append(indent).append(line).append('\n');
68  
  }
69  
  
70  
  void indent() {
71  
    indent += "  ";
72  
  }
73  
  
74  
  void unindent() {
75  
    indent = indent.substring(0, indent.length()-2);
76  
  }
77  
  
78  
  void translators(String... ids) {
79  
    for (String id : ids)
80  
      if (! translators.contains(id)) // space is needed otherwise translator 636 is fooled :)
81  
        translators.add(id);
82  
  }
83  
  
84  
  String getTranslators() {
85  
    // TODO: We should really fix the "standard functions" translator
86  
    // to properly find the main class.
87  
    //
88  
    // As a hack, we move it upwards (before classes adding)
89  
    int i = translators.indexOf("!standard functions");
90  
    if (i >= 0) {
91  
      translators.remove(i);
92  
      translators.add(0, "!standard functions");
93  
    }
94  
    
95  
    return main.fromLines(translators);
96  
  }
97  
98  
  String s() {
99  
    return "((String) " + var + ")";
100  
  }
101  
  
102  
  String list() {
103  
    return "((List) " + var + ")";
104  
  }
105  
  
106  
  void assign(String exp) {
107  
    line(var + " = " + exp + ";");
108  
  }
109  
}
110  
111  
main {
112  
  static new List<Case> cases;
113  
  static new HashMap<String, Case> casesByID;
114  
  static boolean testJava = true, showFails;
115  
  static new (Hash)Set<String> parseErrors;
116  
  static int caseIdx;
117  
  
118  
  psvm {
119  
    new List<String> snippetIDs;
120  
    
121  
    for (int i = 0; i < args.length; i++) {
122  
      String arg = args[i];
123  
      if (arg.equals("debug"))
124  
        debugOn(args[++i]);
125  
      else if (arg.equals("-notestjava"))
126  
        testJava = false;
127  
      else if (arg.equals("-testjava"))
128  
        testJava = true;
129  
      else if (arg.equals("-showfails"))
130  
        showFails = true;
131  
      else if (isSnippetID(arg))
132  
        snippetIDs.add(arg);
133  
      else
134  
        System.err.println("Unknown argument: " + arg + ", ignoring");
135  
    }
136  
    
137  
    if (snippetIDs.isEmpty())
138  
      parse(null);
139  
    
140  
    for (String snippetID : snippetIDs)
141  
      try {
142  
        parse(snippetID);
143  
      } catch (Throwable e) {
144  
        e.printStackTrace();
145  
        parseErrors.add(snippetID);
146  
      }
147  
    
148  
    int solved = 0, n = cases.size(), goodJava = 0;
149  
    for (caseIdx = 0; caseIdx < n; caseIdx++) {
150  
      Case case = cases.get(caseIdx);
151  
      try {
152  
        calculate(case);
153  
      } catch (Throwable e) {
154  
        e.printStackTrace();
155  
      }
156  
      if (case.winner != null)
157  
        ++solved;
158  
      if (case.goodJava)
159  
        ++goodJava;
160  
      System.out.println((caseIdx+1) + " case(s) processed, " + solved + " solved.");
161  
      if (testJava && goodJava < solved)
162  
        System.out.println((solved-goodJava) + " case(s) with BAD JAVA.");
163  
    }
164  
165  
    print ""    
166  
    print "----"
167  
168  
    boolean allSolved = solved == n;
169  
    if (solved != 0) {
170  
      System.out.println();
171  
      System.out.print("Solved: ");
172  
      for (Case case : cases)
173  
        if (case.winner != null)
174  
          System.out.print(case.id + " ");
175  
      System.out.println();
176  
    }
177  
    if (testJava && solved > goodJava) {
178  
      System.out.println();
179  
      System.out.print("Bad Java: ");
180  
      for (Case case : cases)
181  
        if (case.winner != null && !case.goodJava)
182  
          System.out.print(case.id + " ");
183  
      System.out.println();
184  
    }
185  
    if (!allSolved) {
186  
      System.out.println();
187  
      System.out.print("Unsolved: ");
188  
      for (Case case : cases)
189  
        if (case.winner == null)
190  
          System.out.print(case.id + " ");
191  
      System.out.println();
192  
    }
193  
    if (!parseErrors.isEmpty()) {
194  
      System.out.print("\nParse errors: ");
195  
      for (String id : parseErrors)
196  
          System.out.print(id + " ");
197  
      System.out.println();
198  
    }
199  
    System.out.println();
200  
    if (allSolved && testJava && goodJava < solved)
201  
      System.out.println("All solved (" + solved + "), but some BAD JAVA.");
202  
    else {
203  
      System.out.println(allSolved ? "ALL SOLVED (" + solved + ")" : "Solved " + solved + " out of " + n + ".");
204  
      if (testJava)
205  
        if (goodJava == solved)
206  
          System.out.println("All Java code OK" + (allSolved ? "" : " (for solved cases)") + ".");
207  
        else
208  
          System.out.println("Some bad Java.");
209  
      else
210  
        System.out.println("Java not tested.");
211  
    }
212  
    print ""
213  
  }
214  
  
215  
  static class Case {
216  
    String id;
217  
    new List<String[]> fullExamples;
218  
    new List<String> halfExamples;
219  
    List<String[]> examples1, examples2;
220  
    Learner winner;
221  
    boolean goodJava;
222  
    List<Case> combined;
223  
    int splitPoint = -1;
224  
225  
    void split() {    
226  
      if (examples1 != null)
227  
        return; // already done
228  
      if (fullExamples.size() < 2)
229  
        throw new RuntimeException("Too few examples (" + fullExamples.size() + ")");
230  
      if (splitPoint < 0)
231  
        splitPoint = fullExamples.size()-1;
232  
      System.out.println("Full examples: " + fullExamples.size() + ", splitPoint: " + splitPoint);
233  
      examples1 = fullExamples.subList(0, splitPoint);
234  
      examples2 = fullExamples.subList(splitPoint, fullExamples.size());
235  
    }
236  
    
237  
    void add(Case case) {
238  
      combined.add(case);
239  
      fullExamples.addAll(case.fullExamples);
240  
      halfExamples.addAll(case.halfExamples);
241  
    }
242  
  }
243  
244  
  static Case parse(String arg) tex {
245  
    new Case case;
246  
    String text;
247  
    if (arg != null) {
248  
      if (casesByID.containsKey(arg))
249  
        return casesByID.get(arg);
250  
        
251  
      if (arg.startsWith("Combine")) {
252  
        case.id = "Combine";
253  
        case.combined = new ArrayList<Case>();
254  
        List<String> tok = JavaTok.split(arg);
255  
        new List<String> ids;
256  
        for (int i = 5; i < tok.size(); i += 6) { // skip # and "and"
257  
          Case case2 = parse("#" + tok.get(i));
258  
          case.id += " #" + tok.get(i);
259  
          cases.remove(case2);
260  
          case.add(case2);
261  
        }
262  
        addCase(case);
263  
        return case;
264  
      } else {
265  
        case.id = arg;
266  
        text = loadSnippet(arg);
267  
      }
268  
    } else {
269  
      case.id = "input.txt";
270  
      text = loadTextFile("input/input.txt", null);
271  
      if (text == null) {
272  
        //case.id = "#2000455";  // example input
273  
        case.id = "#681"; // a collection of "all cases"!
274  
        text = loadSnippet(case.id);
275  
      }
276  
    }
277  
    
278  
    // it's a collection of cases!
279  
    if (text.trim().startsWith("#") || text.trim().startsWith("Combine")) {
280  
      for (String line : toLines(text))
281  
        parse(line);
282  
      return null;
283  
    }
284  
    
285  
    // it's a "Continue:" task - transform to I/O format
286  
    if (text.trim().startsWith("Continue:")) {
287  
      List<String> lines = toLines(text);
288  
      new StringBuilder buf;
289  
      for (int i = 1; i < lines.size(); i++) {
290  
        buf.append("In: " + quote("" + i) + "\n");
291  
        buf.append("Out: " + quote(lines.get(i)) + "\n");
292  
      }
293  
      int numAsking = 3;
294  
      for (int i = lines.size(); i < lines.size()+numAsking; i++)
295  
        buf.append("In: " + quote("" + i) + "\n");
296  
      text = buf.toString();
297  
    }
298  
      
299  
    // it's a "Execute." task - run Java(X) and transform to I/O format
300  
    if (text.trim().startsWith("Execute.")) {
301  
      List<String> tok = JavaTok.split(text);
302  
      new StringBuilder buf;
303  
      for (int i = 5; i < tok.size(); i += 2) {
304  
        if (tok.get(i).equals("-") && tok.get(i+2).equals("-")) {
305  
          i += 2;
306  
          buf.append("--\n");
307  
        } else {
308  
          String code = unquote(tok.get(i));
309  
          String result = execute("!636\n" + code);
310  
          buf.append("In: " + quote(code) + "\n");
311  
          buf.append("Out: " + quote(result) + "\n");
312  
        }
313  
      }
314  
      text = buf.toString();
315  
    }
316  
      
317  
    System.out.println(text);
318  
    String in = null, out = null;
319  
    
320  
    for (String line : toLines(text)) {
321  
      line = line.trim();
322  
      if (line.equals("--"))
323  
        case.splitPoint = case.fullExamples.size();
324  
      else if (line.toUpperCase().startsWith("I")) { // "In: " or "I: "
325  
        if (in != null)
326  
          case.halfExamples.add(in);
327  
        in = unquote(line.substring(line.indexOf(':')+1).trim());
328  
        out = null;
329  
      } else if (line.toUpperCase().startsWith("O")) { // "Out: " or "O: "
330  
        out = unquote(line.substring(line.indexOf(':')+1).trim());
331  
        System.out.println(quote(in) + " => " + quote(out));
332  
        case.fullExamples.add(new String[] {in, out});
333  
        in = out = null;
334  
      } else {
335  
        System.out.println("-- Ignoring line: " + line);
336  
      }
337  
    }
338  
    
339  
    if (in != null)
340  
      case.halfExamples.add(in);
341  
    addCase(case);
342  
    return case;
343  
  }
344  
  
345  
  static void addCase(Case case) {
346  
    cases.add(case);
347  
    casesByID.put(case.id, case);
348  
  }
349  
  
350  
  static void calculate(Case case) tex {
351  
    System.out.println("\n== CASE " + case.id + " ==");
352  
    
353  
    case.split();
354  
    Learner learner = findOKLearner(case);
355  
    if (learner == null)
356  
      print "\nProblem not solved"
357  
    else {
358  
      print "\nSolved!"
359  
      case.winner = learner;
360  
      new Code code;
361  
      learner.toJava(code);
362  
      
363  
      if (testJava)
364  
        testJava(case, code); // prints "GOOD JAVA" or "BAD JAVA"
365  
      else
366  
        print "Java:"
367  
        
368  
      System.out.println(indent("  ", code.getTranslators()));
369  
      System.out.println(indent("  ", code.buf.toString()));
370  
        
371  
      for (String in : case.halfExamples) {
372  
        Object out = learner.processIn(in);
373  
        System.out.println(quote(in) + " =>! " + quote((String) out));
374  
      }
375  
    }
376  
  }
377  
  
378  
  static Learner findOKLearner(Case case) tex {
379  
    for (Learner learner : makeLearners()) try {
380  
      if (learnerOK(learner, case))
381  
        return learner;
382  
    } catch (Throwable e) {
383  
      if (showFails)
384  
        e.printStackTrace();
385  
    }
386  
    
387  
    if (case.combined != null) {
388  
      Case switchCase = makeSwitchCase(case);
389  
      calculate(switchCase);
390  
      Learner learner = switchCase.winner;
391  
      if (learner != null)
392  
        return new LSwitch(case, learner);
393  
    }
394  
    
395  
    return null;
396  
  }
397  
  
398  
  static Case makeSwitchCase(Case case) {
399  
    int i = 0;
400  
    Case s = new Case();
401  
    s.id = "Switch " + case.id;
402  
    s.examples1 = new ArrayList<String[]>();
403  
    s.examples2 = new ArrayList<String[]>();
404  
    for (Case c : case.combined) {
405  
      ++i;
406  
      for (String[] e : c.examples1)
407  
        s.examples1.add(new String[] {e[0], String.valueOf(i)});
408  
      for (String[] e : c.examples2)
409  
        s.examples2.add(new String[] {e[0], String.valueOf(i)});
410  
      for (String[] e : c.fullExamples)
411  
        s.fullExamples.add(new String[] {e[0], String.valueOf(i)});
412  
    }
413  
    return s;
414  
  }
415  
  
416  
  static boolean learnerOK(Learner learner, Case case) {
417  
    String[] _e = null;
418  
    try {
419  
      if (case.examples1 == null)
420  
        fail("Case not calculated: " + case.id);
421  
      for (String[] e : case.examples1) {
422  
        _e = e;
423  
        learner.processInOut(e[0], e[1]);
424  
      }
425  
      
426  
      // full validation against all examples
427  
      for (String[] e : case.fullExamples) {
428  
        _e = e;
429  
        String out = (String) learner.processIn(e[0]);
430  
        if (!e[1].equals(out)) {
431  
          if (showFails)
432  
            System.out.println("[fail] " + learner + " on " + quote(e[0]) + " - got: " + quote(out) + " rather than: " + quote(e[1]));
433  
          return false;
434  
        }
435  
      }
436  
      return true; // all test examples passed
437  
    } catch (Throwable e) {
438  
      if (showFails) {
439  
        e.printStackTrace();
440  
        System.err.println("[fail] " + learner + " on " + (_e == null ? "?" : quote(_e[0])) + " - " + e);
441  
      }
442  
      return false;
443  
    }
444  
  }
445  
  
446  
  static boolean validate(String[] example, Learner learner) {
447  
    try {
448  
      String out = (String) learner.processIn(example[0]);
449  
      if (!example[1].equals(out)) {
450  
          //System.out.println("[fail] " + learner + " on " + quote(e[0]) + " - got: " + quote(out) + " rather than: " + quote(e[1]));
451  
          return false;
452  
        }
453  
      return true;
454  
    } catch (Throwable e) {
455  
      silentException(e);
456  
      return false;
457  
    }
458  
  }
459  
  
460  
  static void silentException(Throwable e) {
461  
  }
462  
  
463  
  /* XXX - important part */
464  
  static Iterable<Learner> makeLearners() {
465  
    new List<Learner> list;
466  
    //list.add(new LId()); // subsumed by trivial case of PrefixSuffix
467  
    list.add(new LPrefixSuffix());
468  
    list.add(new LSplitInput(new LOutPattern()));
469  
    list.add(new LInputPattern());
470  
    list.add(new LFixed());
471  
    list.add(new LBoth(new RFJavaTok(), new LEach(new LFixedFunction(new EscapeCase()))));
472  
    list.add(new LCharShift());
473  
    list.add(new LOutSuffix(new LFirst(new LCharShift())));
474  
    list.add(new LChange(new RFJavaTok(),
475  
      new LChange(new FStringsOnly(),
476  
        new LGetListElement())));
477  
    list.add(new LChange(new RFJavaTok(),
478  
      new LChange(new FNumbersOnly(), new LMath())));
479  
      
480  
    // of no use now it seems
481  
    // list.add(new LTryPrevious());
482  
    return list;
483  
  }
484  
  
485  
  public static String unquote(String s) {
486  
    if (s.startsWith("[[") && s.endsWith("]]"))
487  
      return s.substring(2, s.length()-2);
488  
    else if (s.startsWith("\"") && s.endsWith("\"") && s.length() > 1)
489  
      return s.substring(1, s.length()-1).replace("\\\"", "\"").replace("\\\\", "\\"); // SHOULD work...
490  
    else
491  
      return s; // return original
492  
  }
493  
  
494  
  public static String quote(String s) {
495  
    if (s == null) return "null";
496  
    return "\"" + s.replace("\\", "\\\\").replace("\"", "\\\"") + "\"";
497  
  }
498  
  
499  
  static String indent(String indent, String s) {
500  
    return indent + s.replace("\n", "\n" + indent);
501  
  }
502  
  
503  
  static void debugOn(String name) {
504  
    try {
505  
      Class c = Class.forName("main$" + name);
506  
      Field field;
507  
      while (true)
508  
        try {
509  
          field = c.getDeclaredField("debug");
510  
          break;
511  
        } catch  (NoSuchFieldException e) {
512  
          c = c.getSuperclass();
513  
        }
514  
      field.setBoolean(null, true);
515  
    } catch (Exception e) {
516  
      e.printStackTrace();
517  
      System.err.println("Cannot debug class " + name);
518  
    }
519  
  }
520  
  
521  
  // splits the input at some point, takes only one part
522  
  static class LSplitInput implements Learner {
523  
    int splitIdx = 1; // split after first character
524  
    Learner baseLearner;
525  
    
526  
    LSplitInput(Learner baseLearner) {
527  
      this.baseLearner = baseLearner;
528  
    }
529  
    
530  
    public void processInOut(Object _in, Object _out) {
531  
      String in = (String) _in, out = (String) _out;
532  
      in = in.substring(splitIdx);
533  
      baseLearner.processInOut(in, out);
534  
    }
535  
    
536  
    public Object processIn(Object _in) {
537  
      String in = (String) _in;
538  
      in = in.substring(splitIdx);
539  
      return baseLearner.processIn(in);
540  
    }
541  
    
542  
    public void toJava(Code code) {
543  
      if (splitIdx != 0)
544  
        code.line(code.var + " = ((String) " + code.var + ").substring(" + splitIdx + ");");
545  
      baseLearner.toJava(code);
546  
    }
547  
  }
548  
  
549  
  // removes common suffix from out, delegates to base learner
550  
  static class LOutSuffix implements Learner {
551  
    String suffixOut = "";
552  
    Learner baseLearner;
553  
    
554  
    LOutSuffix(Learner baseLearner) {
555  
      this.baseLearner = baseLearner;
556  
    }
557  
    
558  
    public void processInOut(Object _in, Object _out) {
559  
      String in = (String) _in, out = (String) _out;
560  
      if (out.endsWith("!"))
561  
        suffixOut = "!";
562  
      if (out.endsWith(suffixOut))
563  
        out = out.substring(0, out.length()-suffixOut.length());
564  
      
565  
      baseLearner.processInOut(in, out);
566  
    }
567  
    
568  
    public Object processIn(Object _in) {
569  
      String in = (String) _in;
570  
      return baseLearner.processIn(in) + suffixOut;
571  
    }
572  
    
573  
    public void toJava(Code code) {
574  
      baseLearner.toJava(code);
575  
      if (suffixOut.length() != 0)
576  
        code.line(code.var + " = " + code.s() + "+" + quote(suffixOut) + ";");
577  
    }
578  
  }
579  
  
580  
  // if input appears in output in fixed pattern
581  
  static class LOutPattern implements Learner {
582  
    String pattern = "%!%";
583  
584  
    public void processInOut(Object _in, Object _out) {
585  
      String in = (String) _in, out = (String) _out;
586  
      pattern = out.replace(in, "%!%");
587  
    }
588  
    
589  
    public String processIn(Object _in) {
590  
      String in = (String) _in;
591  
      return pattern.replace("%!%", in);
592  
    }
593  
    
594  
    public void toJava(Code code) {
595  
      code.line(code.var + " = " + quote(pattern) + ".replace(" + quote("%!%") + ", (String) " + code.var + ");");
596  
    }
597  
  }
598  
  
599  
  // learns to exchange common prefixes and suffixes
600  
  static class LPrefixSuffix extends LearnerImpl {
601  
    static boolean debug;
602  
    String prefixIn, suffixIn, prefixOut, suffixOut;
603  
    
604  
    public void processInOut(Object _in, Object _out) {
605  
      String in = (String) _in, out = (String) _out;
606  
      updateIn(in);
607  
      prefixOut = prefixOut == null ? out : commonPrefix(prefixOut, out);
608  
      suffixOut = suffixOut == null ? out : commonSuffix(suffixOut, out);
609  
      if (debug)
610  
        printState("processInOut(" + quote(in) + ", " + quote(out) + ")");
611  
    }
612  
    
613  
    void updateIn(String in) {
614  
      prefixIn = prefixIn == null ? in : commonPrefix(prefixIn, in);
615  
      suffixIn = suffixIn == null ? in : commonSuffix(suffixIn, in);
616  
      if (debug)
617  
        printState("updateIn(" + quote(in) + ")");
618  
    }
619  
620  
    public String processIn(Object _in) {
621  
      String in = (String) _in;
622  
      //System.out.println("[before last info] " + quote(prefixIn) + " " + quote(suffixIn) + " " + quote(prefixOut) + " " + quote(suffixOut));
623  
      //System.out.println("[last info] " + quote(in));
624  
      
625  
      // use latest information
626  
      String p = prefixIn, s = suffixIn;
627  
      updateIn(in);
628  
      prefixOut = prefixOut.substring(0, prefixOut.length()-(p.length()-prefixIn.length()));
629  
      suffixOut = suffixOut.substring(s.length()-suffixIn.length());
630  
      
631  
      //System.out.println("[after last info] " + quote(prefixIn) + " " + quote(suffixIn) + " " + quote(prefixOut) + " " + quote(suffixOut));
632  
      String core = in.substring(prefixIn.length(), in.length()-suffixIn.length());
633  
      return prefixOut + core + suffixOut;
634  
    }
635  
    
636  
    public void toJava(Code code) {
637  
      if (prefixIn.length() != 0 || suffixIn.length() != 0)
638  
        code.line(code.var + " = ((String) " + code.var + ").substring(" + prefixIn.length() + ", " + code.s() + ".length()-" + suffixIn.length() + ");");
639  
      if (prefixOut.length() != 0 || suffixOut.length() != 0)
640  
        code.line(code.var + " = " + quote(prefixOut) + " + " + code.var + " + " + quote(suffixOut) + ";");
641  
    }
642  
    
643  
    void printState(String text) {
644  
      System.out.println(text);
645  
      printVars();
646  
    }
647  
  }
648  
  
649  
  // for "find" tasks (e.g. "abcde" to "[[abc]]de")
650  
  static class LInputPattern implements Learner {
651  
    String regexp = "";
652  
    
653  
    public void processInOut(Object _in, Object _out) {
654  
      String in = (String) _in, out = (String) _out;
655  
      int i = out.indexOf("[["), j = out.indexOf("]]", i+1);
656  
      if (j < 0) return;
657  
      String s = out.substring(i+2, j);
658  
      regexp = s.replaceAll("\\d+", Matcher.quoteReplacement("\\d+"));
659  
      System.out.println("regexp: " + regexp);
660  
    }
661  
    
662  
    public String processIn(Object _in) {
663  
      String in = (String) _in;
664  
      if (regexp.length() == 0)
665  
        return in;
666  
      else
667  
        return in.replaceAll("(" + regexp + ")", "[[$1]]");
668  
    }
669  
    
670  
    public void toJava(Code code) {
671  
      code.line(code.var + " = ((String) " + code.var + ").replaceAll(" + quote("(" + regexp + ")") + ", \"[[$1]]\");");
672  
    }
673  
  }
674  
  
675  
  static class LFixed extends LearnerImpl {
676  
    static boolean debug;
677  
    Object value;
678  
    
679  
    public void processInOut(Object in, Object out) {
680  
      value = out;
681  
      if (debug)
682  
        printVars();
683  
    }
684  
    
685  
    public Object processIn(Object in) {
686  
      return value;
687  
    }
688  
    
689  
    public void toJava(Code code) {
690  
      code.line(code.var + " = " + quote((String) value) + ";");
691  
    }
692  
  }
693  
  
694  
  static void fail(String msg) {
695  
    throw new RuntimeException(msg);
696  
  }
697  
  
698  
  static void assertSameSize(List a, List b) {
699  
    if (a.size() != b.size())
700  
      fail("wrong list sizes");
701  
  }
702  
703  
  // process lists in parallel
704  
  // (in and out must be a list of same length)
705  
  static class LEach extends LearnerImpl {
706  
    static boolean debug;
707  
    Learner base;
708  
    
709  
    LEach(Learner base) {
710  
      this.base = base;
711  
    }
712  
    
713  
    public void processInOut(Object _in, Object _out) {
714  
      List in = (List) _in, out = (List) _out;
715  
      assertSameSize(in, out);
716  
      for (int i = 0; i < in.size(); i++)
717  
        base.processInOut(in.get(i), out.get(i));
718  
      if (debug)
719  
        printVars();
720  
    }
721  
    
722  
    public Object processIn(Object _in) {
723  
      List in = (List) _in;
724  
      List out = new ArrayList();
725  
      for (Object x : in)
726  
        out.add(base.processIn(x));
727  
      return out;
728  
    }
729  
    
730  
    public void toJava(Code code) {
731  
      code.line("List out = new ArrayList();");
732  
      code.line("for (Object x : (List) in) {");
733  
      code.indent();
734  
      code.line("in = x;");
735  
      base.toJava(code);
736  
      code.line("out.add(in);");
737  
      code.unindent();
738  
      code.line("}");
739  
      code.line("in = out;");
740  
    }
741  
  }
742  
  
743  
  static class LChange extends LearnerImpl {
744  
    Function f;
745  
    Learner base;
746  
    
747  
    LChange(Function f, Learner base) {
748  
      this.f = f;
749  
      this.base = base;
750  
    }
751  
    
752  
    public void processInOut(Object in, Object out) {
753  
      in = f.process(in);
754  
      base.processInOut(in, out);
755  
    }
756  
    
757  
    public Object processIn(Object in) {
758  
      in = f.process(in);
759  
      return base.processIn(in);
760  
    }
761  
    
762  
    public void toJava(Code code) {
763  
      f.toJava_process(code);
764  
      base.toJava(code);
765  
    }
766  
  }
767  
  
768  
  static class LBoth extends LearnerImpl {
769  
    ReversibleFunction f;
770  
    Learner base;
771  
    
772  
    LBoth(ReversibleFunction f, Learner base) {
773  
      this.f = f;
774  
      this.base = base;
775  
    }
776  
    
777  
    public void processInOut(Object in, Object out) {
778  
      in = f.process(in);
779  
      out = f.process(out);
780  
      base.processInOut(in, out);
781  
    }
782  
    
783  
    public Object processIn(Object in) {
784  
      in = f.process(in);
785  
      in = base.processIn(in);
786  
      in = f.unprocess(in);
787  
      return in;
788  
    }
789  
    
790  
    public void toJava(Code code) {
791  
      f.toJava_process(code);
792  
      base.toJava(code);
793  
      f.toJava_unprocess(code);
794  
    }
795  
  }
796  
  
797  
  static class RFJavaTok implements ReversibleFunction {
798  
    public Object process(Object in) {
799  
      return JavaTok.split((String) in);
800  
    }
801  
    
802  
    public Object unprocess(Object in) {
803  
      return JavaTok.join((List) in);
804  
    }
805  
    
806  
    public void toJava_process(Code code) {
807  
      code.translators("!636", "!class JavaTok");
808  
      code.line(code.var + " = JavaTok.split((String) " + code.var + ");");
809  
    }
810  
    
811  
    public void toJava_unprocess(Code code) {
812  
      code.translators("!636", "!class JavaTok");
813  
      code.line(code.var + " = JavaTok.join((List) " + code.var + ");");
814  
    }
815  
  }
816  
  
817  
  // works on a token list - makes a list of only the string constants (unquoted)
818  
  static class FStringsOnly implements Function {
819  
    static boolean debug;
820  
    
821  
    public Object process(Object _in) {
822  
      new List<String> tok;
823  
      for (String s : (List<String>) _in) {
824  
        boolean isString = s.startsWith("\"") || s.startsWith("[[");
825  
        if (isString)
826  
          tok.add(unquote(s));
827  
        if (debug)
828  
          System.out.println("FStringsOnly - isString: " + isString + " - " + s);
829  
      }
830  
      return tok;
831  
    }
832  
    
833  
    public void toJava_process(Code code) {
834  
      code.translators("!standard functions");
835  
      code.line("List<String> tok = new ArrayList<String>();");
836  
      code.line("for (String s : (List<String>) " + code.var + ")");
837  
      code.line("  if (s.startsWith(\"\\\"\") || s.startsWith(\"[[\")) tok.add(unquote(s));");
838  
      code.assign("tok");
839  
    }
840  
  }
841  
  
842  
  // works on a token list - makes a list of only the number constants
843  
  static class FNumbersOnly implements Function {
844  
    static boolean debug;
845  
    
846  
    public Object process(Object _in) {
847  
      new List<String> tok;
848  
      for (String s : (List<String>) _in) {
849  
        boolean isNumber = s.length() != 0 && (Character.isDigit(s.charAt(0)) || (s.charAt(0) == '-' && s.length() > 1));
850  
        if (isNumber)
851  
          tok.add(s);
852  
        if (debug)
853  
          System.out.println("FNumbersOnly - isNumber: " + isNumber + " - " + s);
854  
      }
855  
      return tok;
856  
    }
857  
    
858  
    public void toJava_process(Code code) {
859  
      code.line("List<String> tok = new ArrayList<String>();");
860  
      code.line("for (String s : (List<String>) " + code.var + ")");
861  
      code.line("  if (s.length() != 0 && (Character.isDigit(s.charAt(0)) || (s.charAt(0) == '-' && s.length() > 1))) tok.add(s);");
862  
      code.assign("tok");
863  
    }
864  
  }
865  
  
866  
  static class LFixedFunction extends LearnerImpl {
867  
    Function f;
868  
    
869  
    LFixedFunction(Function f) {
870  
      this.f = f;
871  
    }
872  
    
873  
    public void processInOut(Object in, Object out) {
874  
    }
875  
    
876  
    public Object processIn(Object in) {
877  
      return f.process(in);
878  
    }
879  
    
880  
    public void toJava(Code code) {
881  
      f.toJava_process(code);
882  
    }
883  
  }
884  
  
885  
  // trivial stuff like taking the one element out of a 1-element list
886  
  static class LTrivial extends LearnerImpl {
887  
    public void processInOut(Object in, Object out) {
888  
    }
889  
    
890  
    public Object processIn(Object in) {
891  
      return ((List) in).get(0);
892  
    }
893  
    
894  
    public void toJava(Code code) {
895  
      code.assign(code.list() + ".get(0)");
896  
    }
897  
  }
898  
  
899  
  // get element of a list at fixed index
900  
  static class LGetListElement extends LearnerImpl {
901  
    static boolean debug;
902  
    int i;
903  
    
904  
    public void processInOut(Object _in, Object out) {
905  
      List in = (List) _in;
906  
      i = in.indexOf(out);
907  
      if (debug)
908  
        System.out.println("LGetListElement: " + i + " " + out);
909  
    }
910  
    
911  
    public Object processIn(Object in) {
912  
      return ((List) in).get(i);
913  
    }
914  
    
915  
    public void toJava(Code code) {
916  
      code.assign(code.list() + ".get(" + i + ")");
917  
    }
918  
  }
919  
  
920  
  // math operations
921  
  static class LMath extends LearnerImpl {
922  
    static boolean debug;
923  
    String allOperations = "+ - * /";
924  
    new (Tree)Set<String> possibleOperations;
925  
    
926  
    LMath() {
927  
      possibleOperations.addAll(Arrays.asList(allOperations.split(" +")));
928  
    }
929  
    
930  
    public void processInOut(Object _in, Object _out) {
931  
      List in = (List) _in;
932  
      String out = (String) _out;
933  
      BigInteger[] inNumbers = getNumbers(in);
934  
      BigInteger[] outNumbers = new BigInteger[] {getNumber(out)};
935  
      findOperation(inNumbers, outNumbers);
936  
      if (debug)
937  
        System.out.println("Operations: " + possibleOperations);
938  
    }
939  
    
940  
    public void findOperation(BigInteger[] in, BigInteger[] out) {
941  
      filterOperations(in, out);
942  
      if (possibleOperations.isEmpty())
943  
        fail("tilt");
944  
    }
945  
      
946  
    public void filterOperations(BigInteger[] in, BigInteger[] out) {
947  
      for (Iterator<String> i = possibleOperations.iterator(); i.hasNext(); ) {
948  
        String op = i.next();
949  
        BigInteger[] out2 = doOperation(op, in);
950  
        if (out2 == null || !arraysEqual(out, out2))
951  
          i.remove(); // keep only matching operations
952  
      }
953  
    }
954  
    
955  
    public BigInteger[] doOperation(String op, BigInteger[] in) {
956  
      op = op.intern();
957  
      try {
958  
        if (in.length == 2) {
959  
          BigInteger a = in[0], b = in[1], x = null;
960  
          if (op == "+")
961  
            x = a.add(b);
962  
          else if (op == "-")
963  
            x = a.subtract(b);
964  
          else if (op == "*")
965  
            x = a.multiply(b);
966  
          else if (op == "/")
967  
            x = a.divide(b);
968  
          return x != null ? new BigInteger[] {x} : null;
969  
        }
970  
        return null;
971  
      } catch (Throwable e) {
972  
        return null;
973  
      }
974  
    }
975  
    
976  
    public String processIn(Object _in) {
977  
      List<String> in = (List<String>) _in;
978  
      String op = possibleOperations.iterator().next();
979  
      if (debug)
980  
        System.out.println("op: " + op);
981  
      BigInteger[] inNumbers = getNumbers(in);
982  
      BigInteger[] outNumbers = doOperation(op, inNumbers);
983  
      return outNumbers[0].toString();
984  
    }
985  
    
986  
    String BI = BigInteger.class.getName();
987  
    
988  
    public void toJava(Code code) {
989  
      String op = possibleOperations.iterator().next();
990  
      String a = "new " + BI + "((String) " + code.list() + ".get(0))";
991  
      String b = "new " + BI + "((String) " + code.list() + ".get(1))";
992  
      if (op.equals("+"))
993  
        code.assign(a + ".add(" + b + ").toString()");
994  
      else
995  
        todo();
996  
    }
997  
    
998  
    static BigInteger[] getNumbers(List<String> in) {
999  
      BigInteger[] big = new BigInteger[in.size()];
1000  
      for (int i = 0; i < in.size(); i++)
1001  
        big[i] = new BigInteger(in.get(i));
1002  
      return big;
1003  
    }
1004  
    
1005  
    static BigInteger getNumber(String s) {
1006  
      return new BigInteger(s);
1007  
    }
1008  
    
1009  
    static boolean arraysEqual(BigInteger[] a, BigInteger[] b) {
1010  
      if (a.length != b.length) return false;
1011  
      for (int i = 0; i < a.length; i++)
1012  
        if (!a[i].equals(b[i])) return false;
1013  
      return true;
1014  
    }
1015  
  }
1016  
  
1017  
  static class EscapeCase implements Function {
1018  
    static boolean debug;
1019  
    
1020  
    public Object process(Object _in) {
1021  
      if (debug)
1022  
        System.out.println("EscapeCase: " + _in);
1023  
      String in = (String) _in;
1024  
      return in.equals("case") ? "_case" : in;
1025  
    }
1026  
    
1027  
    public void toJava_process(Code code) {
1028  
      code.line("if (\"case\".equals(" + code.var + ")) " + code.var + " = " + quote("_case") + ";");
1029  
    }
1030  
  }
1031  
  
1032  
  static class LCharShift extends LearnerImpl {
1033  
    int shift;
1034  
    
1035  
    public void processInOut(Object _in, Object _out) {
1036  
      String in = (String) _in, out = (String) _out;
1037  
      shift = (int) out.charAt(0) - (int) in.charAt(0);
1038  
    }
1039  
    
1040  
    public Object processIn(Object _in) {
1041  
      String in = (String) _in;
1042  
      char[] c = new char[in.length()];
1043  
      for (int i = 0; i < c.length; i++)
1044  
        c[i] = (char) ((int) in.charAt(i) + shift);
1045  
      return new String(c);
1046  
    }
1047  
    
1048  
    public void toJava(Code code) {
1049  
      code.line("char[] c = new char[((String) " + code.var + ").length()];");
1050  
      code.line("for (int i = 0; i < c.length; i++)");
1051  
      code.line("  c[i] = (char) ((int) ((String) " + code.var + ").charAt(i)" + (shift < 0 ? "" + shift : "+" + shift) + ");");
1052  
      code.line(code.var + " = new String(c);");
1053  
    }
1054  
  }
1055  
  
1056  
  // applies base learner to first char of string
1057  
  // (or first element of list, TODO)
1058  
  static class LFirst implements Learner {
1059  
    Learner baseLearner;
1060  
    
1061  
    LFirst(Learner baseLearner) {
1062  
      this.baseLearner = baseLearner;
1063  
    }
1064  
    
1065  
    public void processInOut(Object _in, Object _out) {
1066  
      String in = (String) _in, out = (String) _out;
1067  
      if (in.length() == 0)
1068  
        return;
1069  
      String firstIn = in.substring(0, 1), firstOut = out.substring(0, 1);
1070  
      baseLearner.processInOut(firstIn, firstOut);
1071  
    }
1072  
    
1073  
    public Object processIn(Object _in) {
1074  
      String in = (String) _in;
1075  
      if (in.length() == 0)
1076  
        return in;
1077  
      String firstIn = in.substring(0, 1);
1078  
      return baseLearner.processIn(firstIn) + in.substring(1);
1079  
    }
1080  
    
1081  
    public void toJava(Code code) {
1082  
      code.line("if (" + code.s() + ".length() != 0) {");
1083  
      code.indent();
1084  
      code.line("String rest = " + code.s() + ".substring(1);");
1085  
      code.line(code.var + " = " + code.s() + ".substring(0, 1);");
1086  
      baseLearner.toJava(code);
1087  
      code.line(code.var + " = " + code.s() + "+rest;");
1088  
      code.unindent();
1089  
      code.line("}");
1090  
    }
1091  
  }
1092  
  
1093  
  static Method findMainMethod(Class<?> theClass) {
1094  
    for (Method method : theClass.getMethods())
1095  
      if (method.getName().equals("main") && method.getParameterTypes().length == 1)
1096  
        return method;
1097  
    throw new RuntimeException("Method 'main' with 1 parameter not found in " + theClass.getName());
1098  
  }
1099  
  
1100  
  // compile JavaX source and load main class
1101  
  static Class<?> loadMainClass(String src) tex {
1102  
    File srcDir = _x16.TempDirMaker_make();
1103  
    File classesDir = _x16.TempDirMaker_make();
1104  
    _x16.saveTextFile(new File(srcDir, "main.java").getPath(), src);
1105  
    new List<File> libraries;
1106  
    File transpiledDir = _x16.topLevelTranslate(srcDir, libraries);
1107  
    String javacOutput = _x16.compileJava(transpiledDir, libraries, classesDir);
1108  
    System.out.println(javacOutput);
1109  
    URL[] urls = {classesDir.toURI().toURL()};
1110  
    
1111  
    // make class loader
1112  
    URLClassLoader classLoader = new URLClassLoader(urls);
1113  
1114  
    // load main class
1115  
    Class<?> mainClass = classLoader.loadClass("main");
1116  
    return mainClass;
1117  
  }
1118  
      
1119  
  static Method compileJavaInToOut(Code code) {
1120  
    try {
1121  
      String java = code.buf.toString();
1122  
      String prelude = /*"import java.util.*;\n\n" +*/
1123  
        "public class main { public static Object main(Object in) throws Exception {\n";
1124  
      String postlude = "\nreturn in;\n}}";
1125  
      String src = code.getTranslators() + "\n" + prelude + java + postlude;
1126  
      Class<?> mainClass = loadMainClass(src);
1127  
      return findMainMethod(mainClass);
1128  
    } catch (Exception e) {
1129  
      throw new RuntimeException(e);
1130  
    }
1131  
  }
1132  
  
1133  
  static Method findCalcMethod(Class<?> theClass) {
1134  
    for (Method method : theClass.getMethods())
1135  
      if (method.getName().equals("calc"))
1136  
        return method;
1137  
    throw new RuntimeException("Method 'calc' not found in " + theClass.getName());
1138  
  }
1139  
  
1140  
  // for simplejava stuff (execute tasks)
1141  
  static String execute(String src) {
1142  
    try {
1143  
      Class<?> mainClass = loadMainClass(src);
1144  
      Method m = findCalcMethod(mainClass);
1145  
      return String.valueOf(m.invoke(null));
1146  
    } catch (Exception e) {
1147  
      throw new RuntimeException(e);
1148  
    }
1149  
  }
1150  
  
1151  
  static void testJava(Case case, Code code) {
1152  
    try {
1153  
      Method m = compileJavaInToOut(code);
1154  
      
1155  
      for (String[] e : case.fullExamples) {
1156  
        String out = (String) m.invoke(null, e[0]);
1157  
        
1158  
        if (!e[1].equals(out)) {
1159  
          throw new RuntimeException("[fail] Java code on " + quote(e[0]) + " - got: " + quote(out) + " rather than: " + quote(e[1]));
1160  
        }
1161  
      }
1162  
      
1163  
      System.out.println("\nGOOD JAVA.");
1164  
      case.goodJava = true;
1165  
    } catch (Throwable e) {
1166  
      if (showFails)
1167  
        e.printStackTrace();
1168  
      System.out.println("\nBAD JAVA.");
1169  
    }
1170  
  }
1171  
  
1172  
  static void todo() {
1173  
    fail("todo");
1174  
  }
1175  
  
1176  
  static class LSwitch extends LearnerImpl {
1177  
    Case case;
1178  
    Learner switcher;
1179  
    
1180  
    LSwitch(Case case, Learner switcher) {
1181  
      this.case = case;
1182  
      this.switcher = switcher;
1183  
    }
1184  
    
1185  
    public void processInOut(Object in, Object out) {
1186  
    }
1187  
   
1188  
    public Object processIn(Object in) {
1189  
      int i = Integer.parseInt((String) switcher.processIn(in));
1190  
      return case.combined.get(i-1).winner.processIn(in);
1191  
    }
1192  
   
1193  
    public void toJava(Code code) {
1194  
      todo();
1195  
    }
1196  
  }
1197  
 
1198  
  static class LTryPrevious extends LearnerImpl {
1199  
    new List<Case> candidates;
1200  
    
1201  
    LTryPrevious() {
1202  
      for (int i = caseIdx-1; i >= 0; i--)
1203  
        candidates.add(cases.get(i));
1204  
    }
1205  
1206  
    public void processInOut(Object _in, Object _out) {
1207  
      String in = (String) _in, out = (String) _out;
1208  
      for (ListIterator<Case> i = candidates.listIterator(); i.hasNext(); ) {
1209  
        Case case = i.next();
1210  
        if (case.winner == null || !validate(new String[] {in, out}, case.winner))
1211  
          i.remove();
1212  
      }
1213  
      if (candidates.isEmpty())
1214  
        fail("no previous solution found");
1215  
    }
1216  
  
1217  
    public Object processIn(Object in) {
1218  
      return candidates.get(0).winner.processIn(in);
1219  
    }
1220  
  
1221  
    public void toJava(Code code) {
1222  
      candidates.get(0).winner.toJava(code);
1223  
    }
1224  
  }
1225  
}

Author comment

Began life as a copy of #691

download  show line numbers  debug dex  old transpilations   

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

No comments. add comment

Snippet ID: #693
Snippet name: IOIOI Processor (v8, developing)
Eternal ID of this version: #693/1
Text MD5: 35b6d5f224cb5d4336b92f451008be90
Author: stefan
Category:
Type: JavaX source code
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2015-07-31 00:21:47
Source code size: 37558 bytes / 1225 lines
Pitched / IR pitched: No / Yes
Views / Downloads: 644 / 569
Referenced in: [show references]