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

2264
LINES

< > BotCompany Repo | #722 // IOIOI Processor (v15)

JavaX source code [tags: use-pretranspiled] - run with: x30.jar

Libraryless. Compilation Failed (6398L/43K).

1  
!1001834 // custom translator!
2  
3  
import java.math.*; // BigInteger
4  
import java.text.DecimalFormat;
5  
6  
!include #1000451 // class _x18 modified for Android
7  
8  
!include #728 // class JsonTok
9  
10  
class JavaTok {
11  
  static L<S> split(S s) { ret main.javaTok(s); }
12  
  static S join(L<S> tok) { ret main.join(tok); }
13  
}
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  
  public void tryAgain();
31  
}
32  
33  
abstract class Base {
34  
  void printVars() {
35  
    new StringBuilder buf;
36  
    Field[] fields = getClass().getDeclaredFields();
37  
    for (Field field : fields) {
38  
      if ((field.getModifiers() & Modifier.STATIC) != 0)
39  
        continue;
40  
      Object value;
41  
      try {
42  
        value = field.get(this);
43  
      } catch (Exception e) {
44  
        value = "?";
45  
      }
46  
      
47  
      if (!buf.isEmpty()) buf.append(", ");
48  
      buf.append(field.getName() + "=" + value);
49  
    }
50  
    System.out.println(buf.toString());
51  
  }
52  
  
53  
  String name() {
54  
    return getClass().getName().replaceAll("^main\\$", "");
55  
  }
56  
  
57  
  void debug(String s) {
58  
    System.out.println(name() + ": " + s);
59  
  }
60  
}
61  
62  
abstract class LearnerImpl extends Base implements Learner {
63  
  public void tryAgain() {
64  
    throw new RuntimeException("No try again");
65  
  }
66  
  
67  
  public void toJava(Code code) {
68  
    main.todo();
69  
  }
70  
}
71  
72  
abstract class FunctionImpl extends Base implements Function {
73  
  public void toJava_process(Code code) {
74  
    main.todo();
75  
  }
76  
}
77  
78  
abstract class ReversibleFunctionImpl extends FunctionImpl implements ReversibleFunction {
79  
  public void toJava_unprocess(Code code) {
80  
    main.todo();
81  
  }
82  
}
83  
84  
class Code {
85  
  new StringBuilder buf;
86  
  String var = "in";
87  
  String indent = "";
88  
  new List<String> translators;
89  
  new List<String> varStack;
90  
  int varCounter;
91  
  
92  
  *() {
93  
    translators.add("!636");
94  
  }
95  
  
96  
  void line(String line) {
97  
    buf.append(indent).append(line).append('\n');
98  
  }
99  
  
100  
  void indent() {
101  
    indent += "  ";
102  
  }
103  
  
104  
  void unindent() {
105  
    indent = indent.substring(0, indent.length()-2);
106  
  }
107  
  
108  
  void translators(String... ids) {
109  
    for (String id : ids)
110  
      if (! translators.contains(id)) // space is needed otherwise translator 636 is fooled :)
111  
        translators.add(id);
112  
  }
113  
  
114  
  String getTranslators() {
115  
    // TODO: We should really fix the "standard functions" translator
116  
    // to properly find the main class.
117  
    //
118  
    // As a hack, we move it upwards (before classes adding)
119  
    int i = translators.indexOf("!standard functions");
120  
    if (i >= 0) {
121  
      translators.remove(i);
122  
      translators.add(0, "!standard functions");
123  
    }
124  
    
125  
    return main.fromLines(translators);
126  
  }
127  
128  
  String s() {
129  
    return "((String) " + var + ")";
130  
  }
131  
  
132  
  String list() {
133  
    return "((List) " + var + ")";
134  
  }
135  
  
136  
  void assign(String exp) {
137  
    line(var + " = " + exp + ";");
138  
  }
139  
  
140  
  void newVar() {
141  
    varStack.add(var);
142  
    var = "_v" + (++varCounter);
143  
    line("Object " + var + ";");
144  
  }
145  
  
146  
  void oldVar() {
147  
    var = varStack.get(varStack.size()-1);
148  
    varStack.remove(varStack.size()-1);
149  
  }
150  
}
151  
152  
main {
153  
  // The following field is filled by JavaX.
154  
  static Object androidContext;
155  
156  
  static final String ALL = "#681";
157  
  static final String DEFAULT_STRATEGY = "#1000464";
158  
  static int maxCaseSize = 100000;
159  
  
160  
  static boolean classic = false;
161  
  
162  
  static new List<Case> cases;
163  
  static new HashMap<String, Case> casesByID;
164  
  static boolean testJava = false, showFails, execTasks = false;
165  
  static boolean collectClosest = false; // saves time
166  
  static boolean verboseMonitor = false, extensiveMode = false;
167  
  static boolean verbose;
168  
  static new (Hash)Set<String> parseErrors;
169  
  static int caseIdx;
170  
  static new (Hash)Set<Class> debuggedClasses;
171  
  static String[] innerClasses;
172  
  static new List<Throwable> strategyParseErrors;
173  
  static Learner trying;
174  
  static String user, pass;
175  
  static boolean edit, stayAlive, printStrategy;
176  
  static new List<String> strategies;
177  
178  
  psvm {
179  
   try {
180  
    keepAlive();
181  
    _x18.androidContext = androidContext;
182  
    long startTime = System.currentTimeMillis();
183  
    
184  
    new List<String> snippetIDs;
185  
    new List<String> inputs;
186  
    new List<String> inputDocs;
187  
    new List<Case> userCases;
188  
    
189  
    strategies.add(DEFAULT_STRATEGY);
190  
    
191  
    for (int i = 0; i < args.length; i++) {
192  
      String arg = args[i];
193  
      if (arg.equals("debug"))
194  
        debugOn(args[++i]);
195  
      else if (arg.equals("user"))
196  
        user = args[++i];
197  
      else if (arg.equals("pass")) {
198  
        pass = args[++i];
199  
        args[i] = "hidden";
200  
      } else if (arg.equals("edit"))
201  
        edit = true;
202  
      else if (arg.equals("in")) {
203  
        String in = args[++i];
204  
        //System.out.println("in=" + quote(in));
205  
        String quoteUnquote = unquote("\"" + in + "\"");
206  
        //System.out.println("now in=" + quote(quoteUnquote));
207  
        inputs.add(quoteUnquote);
208  
      } else if (arg.equals("in-doc"))
209  
        inputDocs.add(args[++i]);
210  
      else if (arg.equals("-notestjava"))
211  
        testJava = false;
212  
      else if (arg.equals("-testjava"))
213  
        testJava = true;
214  
      else if (arg.equals("verbose"))
215  
        verbose = true;
216  
      else if (arg.equals("-withexec"))
217  
        execTasks = true;
218  
      else if (arg.equals("-showfails"))
219  
        showFails = true;
220  
      else if (arg.equals("-classic"))
221  
        classic = true;
222  
      else if (arg.equals("-stayalive"))
223  
        stayAlive = true;
224  
      else if (arg.equals("-printstrategy"))
225  
        printStrategy = true;
226  
      else if (arg.equals("strategy"))
227  
        strategies.add(args[++i]);
228  
      else if (arg.equals("onlystrategy")) {
229  
        strategies.clear();
230  
        strategies.add(args[++i]);
231  
      } else if (arg.equals("extensive") || arg.equals("-extensive"))
232  
        extensiveMode = true;
233  
      else if (arg.equals("big"))
234  
        maxCaseSize = Integer.MAX_VALUE;
235  
      else if (arg.equals("all"))
236  
        snippetIDs.add(ALL);
237  
      else if (isSnippetID(arg))
238  
        snippetIDs.add(arg);
239  
      else
240  
        System.err.println("Unknown argument: " + arg + ", ignoring");
241  
    }
242  
    
243  
    if (snippetIDs.isEmpty()) {
244  
      String s = loadTextFile("input/input.txt", null);
245  
      if (s != null)
246  
        parse(s);
247  
      else
248  
        parse(ALL);
249  
    }
250  
    
251  
    for (String snippetID : snippetIDs)
252  
      try {
253  
        Case case = parse(snippetID);
254  
        if (case != null) {
255  
          case.halfExamples.addAll(inputs);
256  
          for (String docID : inputDocs)
257  
            case.halfExamples.add(loadSnippet(docID));
258  
          userCases.add(case);
259  
        }
260  
      } catch (Throwable e) {
261  
        e.printStackTrace();
262  
        parseErrors.add(snippetID);
263  
      }
264  
    
265  
    int solved = 0, n = cases.size(), goodJava = 0;
266  
    for (caseIdx = 0; caseIdx < n; caseIdx++) {
267  
      Case case = cases.get(caseIdx);
268  
      try {
269  
        calculate(case);
270  
      } catch (Throwable e) {
271  
        e.printStackTrace();
272  
      }
273  
      if (case.winner != null)
274  
        ++solved;
275  
      if (case.goodJava)
276  
        ++goodJava;
277  
      if (caseIdx+1 == solved)
278  
        System.out.println((caseIdx+1) + " case(s) processed & solved.");
279  
      else
280  
        System.out.println((caseIdx+1) + " case(s) processed, " + solved + " solved.");
281  
      if (testJava && goodJava < solved)
282  
        System.out.println((solved-goodJava) + " case(s) with BAD JAVA.");
283  
    }
284  
285  
    print ""    
286  
    print "----"
287  
288  
    List<Case> sorted = casesSortedByID();
289  
    boolean allSolved = solved == n;
290  
    if (solved != 0) {
291  
      System.out.println();
292  
      System.out.print("Solved: ");
293  
      for (Case case : sorted)
294  
        if (case.winner != null)
295  
          System.out.print(case.id + " ");
296  
      System.out.println();
297  
    }
298  
    if (testJava && solved > goodJava) {
299  
      System.out.println();
300  
      System.out.print("Bad Java: ");
301  
      for (Case case : sorted)
302  
        if (case.winner != null && !case.goodJava)
303  
          System.out.print(case.id + " ");
304  
      System.out.println();
305  
    }
306  
    if (!allSolved) {
307  
      System.out.println();
308  
      System.out.println("Unsolved:");
309  
      for (Case case : sorted)
310  
        if (case.winner == null)
311  
          System.out.println("  " + case.id + (case.name == null ? "" : " - " + case.name));
312  
    }
313  
    if (!parseErrors.isEmpty()) {
314  
      System.out.print("\nParse errors: ");
315  
      for (String id : parseErrors)
316  
          System.out.print(id + " ");
317  
      System.out.println();
318  
    }
319  
    if (!strategyParseErrors.isEmpty())
320  
      System.out.println("Strategy parse errors!");
321  
    System.out.println();
322  
    if (allSolved && testJava && goodJava < solved)
323  
      System.out.println("ALL SOLVED (" + solved + "), but some BAD JAVA.");
324  
    else {
325  
      System.out.println(allSolved ? "ALL SOLVED (" + solved + ")" : "Solved " + solved + " out of " + n + ".");
326  
      if (testJava)
327  
        if (goodJava == solved)
328  
          System.out.println("All Java code OK" + (allSolved ? "" : " (for solved cases)") + ".");
329  
        else
330  
          System.out.println("Some bad Java.");
331  
      else
332  
        System.out.println("Java not tested.");
333  
    }
334  
    print ""
335  
336  
    if (edit) {
337  
      if (userCases.size() != 1) fail("Edit: More than one user case, confused");
338  
      Case case = userCases.get(0);
339  
      for (String docID : inputDocs) {
340  
        Object _out = case.processIn(loadSnippet(docID));
341  
        if (!(_out instanceof String))
342  
          fail("Case did not generate a string: " + structure(_out));
343  
        String out = cast _out;
344  
        String editInfo = "Solver #" + programID + " " + join(" ", args);
345  
        editSnippetText(docID, out, editInfo);
346  
      }
347  
    }
348  
349  
    /*long time = getUserTime();
350  
    if (time >= 0)
351  
      System.out.println("User time: " + formatDouble(time/1e9, 3) + "s");*/
352  
      
353  
    long time = System.currentTimeMillis()-startTime;
354  
    System.out.println("Real time: " + formatDouble(time/1e3, 3) + "s");
355  
    System.gc();
356  
    Runtime runtime = Runtime.getRuntime();
357  
    System.out.println("Used memory: "
358  
            + (runtime.totalMemory() - runtime.freeMemory()+1024*1024-1) / (1024*1024) + " MB" + ", total: " + (runtime.totalMemory()+1024*1024-1)/(1024*1024) + " MB");
359  
            
360  
    if (stayAlive) {
361  
      System.out.println("Staying alive.");
362  
      Thread.sleep(1000*60*60*24); // for VisualVM and such
363  
    }
364  
   } catch (Throwable e) {
365  
    e.printStackTrace();
366  
   }
367  
  } // end of main method
368  
  
369  
  public static String formatDouble(double d, int digits) {
370  
    String format = "0.";
371  
    for (int i = 0; i < digits; i++) format += "#";
372  
    String s = new DecimalFormat(format).format(d);
373  
    return s.replace(',', '.'); // hack german -> english
374  
  }
375  
  
376  
  /** Get user time in nanoseconds. */
377  
  public static long getUserTime( ) {
378  
    ThreadMXBean bean = ManagementFactory.getThreadMXBean();
379  
    return bean.isCurrentThreadCpuTimeSupported() ?
380  
      bean.getCurrentThreadUserTime() : -1L;
381  
  }
382  
  
383  
  static class Case {
384  
    String id, name;
385  
    new List<Object[]> fullExamples;
386  
    new List<Object> halfExamples;
387  
    List<Object[]> examples1, examples2;
388  
    Learner winner;
389  
    RunnersUp runnersUp = collectClosest ? new RunnersUp() : null;
390  
    boolean goodJava;
391  
    List<Case> combined;
392  
    int splitPoint = -1;
393  
    
394  
    // stats
395  
    int learnersTried, retries;
396  
397  
    void split() {    
398  
      if (examples1 != null)
399  
        return; // already done
400  
      if (fullExamples.size() < 2)
401  
        throw new RuntimeException("Too few examples (" + fullExamples.size() + ")");
402  
      if (splitPoint < 0)
403  
        splitPoint = fullExamples.size()-1;
404  
      System.out.println("Full examples: " + fullExamples.size() + ", splitPoint: " + splitPoint + ", half examples: " + halfExamples.size());
405  
      examples1 = fullExamples.subList(0, splitPoint);
406  
      examples2 = fullExamples.subList(splitPoint, fullExamples.size());
407  
    }
408  
    
409  
    void add(Case case) {
410  
      combined.add(case);
411  
      fullExamples.addAll(case.fullExamples);
412  
      halfExamples.addAll(case.halfExamples);
413  
    }
414  
    
415  
    Object processIn(Object in) {
416  
      return winner.processIn(in);
417  
    }
418  
    
419  
    int size() {
420  
      return structureSize(fullExamples);
421  
    }
422  
    
423  
    static int structureSize(Object o) {
424  
      if (o == null) return 0;
425  
      if (o instanceof String) return ((String) o).length();
426  
      int size = 0;
427  
      if (o instanceof Collection)
428  
        for (Object x : (Collection) o)
429  
          size += structureSize(x);
430  
      else if (o.getClass().isArray()) {
431  
        int n = Array.getLength(o);
432  
        for (int i = 0; i < n; i++)
433  
          size += structureSize(Array.get(o, i));
434  
      }
435  
      return size;
436  
    }
437  
438  
    void checkSize() {    
439  
      int size = size();
440  
      System.out.println("Case size: " + size);
441  
      if (size > maxCaseSize)
442  
        fail("Ignoring case - too big: " + id);
443  
    }
444  
  }
445  
446  
  static Case parse(String arg) throws Exception {
447  
   try {
448  
    if (arg == null) return null;
449  
    arg = arg.trim();
450  
    if (arg.length() == 0) return null;
451  
    new Case case;
452  
    String text;
453  
    
454  
    if (casesByID.containsKey(arg))
455  
      return casesByID.get(arg);
456  
      
457  
    if (arg.startsWith("Combine")) {
458  
      case.id = "Combine";
459  
      case.combined = new ArrayList<Case>();
460  
      List<String> tok = JavaTok.split(arg);
461  
      new List<String> ids;
462  
      for (int i = 5; i < tok.size(); i += 6) { // skip # and "and"
463  
        if (verbose)
464  
          System.out.println("Combine: Parsing " + tok.get(i));
465  
        Case case2 = parse("#" + tok.get(i));
466  
        case.id += " #" + tok.get(i);
467  
        cases.remove(case2);
468  
        case.add(case2);
469  
      }
470  
      addCase(case);
471  
      return case;
472  
    }
473  
    
474  
    if (verbose)
475  
      System.out.println("parse: testing snippet ID");
476  
      
477  
    if (isSnippetID(arg)) {
478  
      case.id = arg;
479  
      String[] x = loadSnippetAndTitle(arg);
480  
      text = x[0];
481  
      case.name = x[1];
482  
    } else {
483  
      case.id = "direct (" + shorten(arg, 10) + ")";
484  
      text = arg;
485  
    }
486  
487  
    if (verbose)
488  
      System.out.println("parse: testing snippet ID done " + quote(text));
489  
      
490  
    // it's a collection of cases!
491  
    if (text.trim().startsWith("#") || text.trim().startsWith("Combine")) {
492  
      for (String line : toLines(text))
493  
        if (isSnippetID(line))
494  
          parse(line);
495  
        else if (line.trim().length() != 0)
496  
          fail("Unknown line: " + line);
497  
      return null;
498  
    }
499  
    
500  
    // it's a "Continue:" task - transform to I/O format
501  
    if (text.trim().startsWith("Continue:")) {
502  
      List<String> lines = toLines(text);
503  
      new StringBuilder buf;
504  
      for (int i = 1; i < lines.size(); i++) {
505  
        buf.append("In: " + quote("" + i) + "\n");
506  
        buf.append("Out: " + quote(lines.get(i)) + "\n");
507  
      }
508  
      int numAsking = 3;
509  
      for (int i = lines.size(); i < lines.size()+numAsking; i++)
510  
        buf.append("In: " + quote("" + i) + "\n");
511  
      text = buf.toString();
512  
    }
513  
      
514  
    // it's an "Execute." task - run Java(X) and transform to I/O format
515  
    if (text.trim().startsWith("Execute.")) {
516  
      if (!execTasks) return null;
517  
      List<String> tok = JavaTok.split(text);
518  
      new StringBuilder buf;
519  
      for (int i = 5; i < tok.size(); i += 2) {
520  
        if (tok.get(i).equals("-") && tok.get(i+2).equals("-")) {
521  
          i += 2;
522  
          buf.append("--\n");
523  
        } else {
524  
          String code = unquote_fixSpaces(tok.get(i));
525  
          String result = execute("!636\n" + code);
526  
          buf.append("In: " + quote(code) + "\n");
527  
          buf.append("Out: " + quote(result) + "\n");
528  
        }
529  
      }
530  
      text = buf.toString();
531  
    }
532  
533  
    if (text.trim().startsWith("Marking.")) {
534  
      
535  
      List<String> tok = JavaTok.split(text);
536  
      new StringBuilder buf;
537  
      for (int i = 5; i < tok.size(); i += 2) {
538  
        if (tok.get(i).equals("-") && tok.get(i+2).equals("-")) {
539  
          i += 2;
540  
          buf.append("--\n");
541  
        } else {
542  
          String out = unquote_fixSpaces(tok.get(i));
543  
          String in = out.replace("[[", "").replace("]]", "");
544  
          buf.append("In: " + quote(in) + "\n");
545  
          buf.append("Out: " + quote(out) + "\n");
546  
        }
547  
      }
548  
      text = buf.toString();
549  
    }
550  
 
551  
    //System.out.println(text);
552  
    String in = null;
553  
    
554  
    if (verbose)
555  
      System.out.println("parse: JavaToking " + quote(text));
556  
    
557  
    List<String> tok = JavaTok.split(text);
558  
    for (int i = 1; i < tok.size(); i += 2) {
559  
      String t = tok.get(i), t2 = i+2 < tok.size() ? tok.get(i+2) : "";
560  
      if (t.equals("-") && t2.equals("-")) {
561  
        i += 2;
562  
        case.splitPoint = case.fullExamples.size();
563  
        //System.out.println("t=" + t + ", t2= " + t2);
564  
      } else if (t.toUpperCase().startsWith("I") && t2.equals("-") && tok.get(i+4).toUpperCase().equals("DOC") && tok.get(i+6).equals(":")) { // "In-Doc:"
565  
        if (in != null)
566  
          case.halfExamples.add(in);
567  
        i += 8;
568  
        int j = findNextLine(tok, i);
569  
        String inID = unquote_fixSpaces(join(tok.subList(i, j-1)));
570  
        in = loadSnippet(inID);
571  
        i = j-2;
572  
      } else if (t.toUpperCase().startsWith("I") && t2.equals(":")) { // "In:" or "I:"
573  
        if (in != null)
574  
          case.halfExamples.add(in);
575  
        i += 4;
576  
        int j = findNextLine(tok, i);
577  
        in = unquote_fixSpaces(join(tok.subList(i, j-1)));
578  
        i = j-2;
579  
      } else if (t.toUpperCase().startsWith("O") && t2.equals(":")) { // "Out: " or "O: "
580  
        i += 4;
581  
        int j = findNextLine(tok, i);
582  
        String out = unquote_fixSpaces(join(tok.subList(i, j-1)));
583  
        i = j-2;
584  
        if ((in + out).indexOf('\t') >= 0)
585  
          System.err.println("WARNING: Tab character used!");
586  
          
587  
        System.out.println(shorten(quote(in), 80) + " => " + shorten(quote(out), 80));
588  
        case.fullExamples.add(new Object[] {in, out});
589  
        case.checkSize();
590  
        in = null;
591  
      } else if (t.toUpperCase().startsWith("O") && t2.equals("-") && tok.get(i+4).toUpperCase().equals("LIST") && tok.get(i+6).equals(":")) { // "Out-List:"
592  
        i += 8;
593  
        if (!tok.get(i).equals("{")) fail("Syntax error in Out-List");
594  
        i += 2;
595  
        new List<String> outList;
596  
        while (!tok.get(i).equals("}")) {
597  
          if (tok.get(i).equals(",")) i += 2;
598  
          if (tok.get(i).equals("}")) break;
599  
          String listEntry = unquote(tok.get(i));
600  
          outList.add(listEntry);
601  
          i += 2;
602  
        }
603  
        System.out.println(shorten(quote(in), 80) + " => list of " + outList.size());
604  
        case.fullExamples.add(new Object[] {in, outList});
605  
        case.checkSize();
606  
        in = null;
607  
      } else {
608  
        int j = findNextLine(tok, i);
609  
        String line = join(tok.subList(i, j-1));
610  
        i = j-2;
611  
        System.out.println("-- Ignoring line: " + line);
612  
      }
613  
    }
614  
    
615  
    if (in != null)
616  
      case.halfExamples.add(in);
617  
    addCase(case);
618  
    return case;
619  
   } catch (Throwable e) {
620  
    parseErrors.add(arg);
621  
    e.printStackTrace();
622  
    return null;
623  
   }
624  
  }
625  
  
626  
  static String unquote_fixSpaces(String s) {
627  
    String _ = unquote(s);
628  
    if (s.startsWith("[["))
629  
      _ = fixSpaces(_);
630  
    return _;
631  
  }
632  
  
633  
  // remove invisible spaces at end of line - this will otherwise confuse the engine(s) greatly...
634  
  static String fixSpaces(String s) {
635  
    System.out.println(quote(s));
636  
    s = s.replaceAll("[\t ]+(\r?\n)", "$1");
637  
    s = s.replaceAll("[\t ]+$", "");
638  
    //System.out.println("_fixSpaces => " + quote(s));
639  
    return s;
640  
  }
641  
  
642  
  // i is a code-token (odd index)
643  
  // return value is also a code token, or end of list
644  
  static int findNextLine(List<String> tok, int i) {
645  
    while (i < tok.size() && tok.get(i-1).indexOf('\n') < 0)
646  
      i += 2;
647  
    return i;
648  
  }
649  
  
650  
  static void addCase(Case case) {
651  
    cases.add(case);
652  
    casesByID.put(case.id, case);
653  
  }
654  
  
655  
  static void calculate(Case case) throws Exception {
656  
    System.out.println("\n== CASE " + case.id + " ==");
657  
    
658  
    case.split();
659  
    Learner learner = findOKLearner(case);
660  
    if (learner == null) {
661  
      String stat = "";
662  
      if (case.retries != 0) stat = " + " + case.retries + " retries";
663  
      System.out.println("\nProblem not solved (" + case.learnersTried + " learners tried" + stat + ")");
664  
      RunnersUp ru = case.runnersUp;
665  
      if (ru != null && ru.winner != null)
666  
        System.out.println("Closest result: " + quote(ru.bestResult) + " instead of " + quote(ru.expected) + " (score " + ru.bestScore + ") by " + structure(ru.winner));
667  
    } else {
668  
      print "\nSolved!"
669  
      int stringSizeLimit = 40;
670  
      print("  " + structure(learner, stringSizeLimit) + "\n");
671  
      case.winner = learner;
672  
      new Code code;
673  
      if (testJava) try {
674  
        learner.toJava(code);
675  
676  
        if (testJava)
677  
          testJava(case, code); // prints "GOOD JAVA" or "BAD JAVA"
678  
        else
679  
          print "Java:"
680  
          
681  
        System.out.println(indent("  ", code.getTranslators()));
682  
        System.out.println(indent("  ", code.buf.toString()));
683  
      } catch (Throwable e) {
684  
        print "BAD JAVA"
685  
      }
686  
        
687  
      for (Object in : case.halfExamples) {
688  
        Object out = learner.processIn(in);
689  
        System.out.println(structure(in) + " =>! " + structure(out));
690  
      }
691  
    }
692  
  }
693  
694  
  static void choice_orderList(List l) {
695  
  }
696  
  
697  
  static Learner findOKLearner(Case case) throws Exception {
698  
    List<Learner> list = makeLearners();
699  
    choice_orderList(list);
700  
    for (Learner learner : list) try {
701  
      if (learnerOK(learner, case))
702  
        return learner;
703  
    } catch (Throwable e) {
704  
      if (showFails)
705  
        e.printStackTrace();
706  
    }
707  
    
708  
    if (case.combined != null) {
709  
      Case switchCase = makeSwitchCase(case);
710  
      calculate(switchCase);
711  
      Learner learner = switchCase.winner;
712  
      if (learner != null)
713  
        return new LSwitch(case, learner);
714  
    }
715  
    
716  
    return null;
717  
  }
718  
  
719  
  static Case makeSwitchCase(Case case) {
720  
    int i = 0;
721  
    Case s = new Case();
722  
    s.id = "Switch " + case.id;
723  
    s.examples1 = new ArrayList<Object[]>();
724  
    s.examples2 = new ArrayList<Object[]>();
725  
    for (Case c : case.combined) {
726  
      ++i;
727  
      for (Object[] e : c.examples1)
728  
        s.examples1.add(new Object[] {e[0], String.valueOf(i)});
729  
      for (Object[] e : c.examples2)
730  
        s.examples2.add(new Object[] {e[0], String.valueOf(i)});
731  
      for (Object[] e : c.fullExamples)
732  
        s.fullExamples.add(new Object[] {e[0], String.valueOf(i)});
733  
    }
734  
    return s;
735  
  }
736  
  
737  
  static boolean learnerOK(Learner learner, Case case) {
738  
    trying = learner;
739  
    
740  
    try {
741  
      Object[] _e = null;
742  
      try {
743  
        if (case.examples1 == null)
744  
          fail("Case not calculated: " + case.id);
745  
          
746  
        ++case.learnersTried;
747  
        for (Object[] e : case.examples1) {
748  
          _e = e;
749  
          learner.processInOut(e[0], e[1]);
750  
        }
751  
        
752  
        // full validation against all examples - but starting with the unknown ones to make coding easier for learners
753  
        int retry = 0;
754  
        retryLoop: while (true) {
755  
          int n = case.fullExamples.size();
756  
          for (int i = 0; i < n; i++) {
757  
            Object[] e = case.fullExamples.get((i+case.examples1.size()) % n);
758  
            _e = e;
759  
            Object out = learner.processIn(e[0]);
760  
            if (!e[1].equals(out)) {
761  
            
762  
              if (case.runnersUp != null && e[1] instanceof String && out instanceof String)
763  
                case.runnersUp.add((String) e[1], (String) out, leven((String) out, (String) e[1]), learner);
764  
                
765  
              if (debuggedClasses.contains(learner.getClass()) || showFails)
766  
                System.out.println("[fail] " + structure(learner) + " on " + structure(e[0]) + " - got: " + structure(out) + " rather than: " + structure(e[1]));
767  
              ++retry;
768  
              ++case.retries;
769  
              if (retry % 1000 == 0)
770  
                System.err.println("Retry " + retry);
771  
              learner.tryAgain();
772  
              continue retryLoop;
773  
            }
774  
          }
775  
          return true;  // all test examples passed
776  
        }
777  
      } catch (Throwable e) {
778  
        if (debuggedClasses.contains(learner.getClass()) || showFails) {
779  
          e.printStackTrace();
780  
          System.err.println("[fail] " + structure(learner) + " on " + (_e == null ? "?" : structure(_e[0])) + " - " + e);
781  
        }
782  
        return false;
783  
      }
784  
    } finally {
785  
      trying = null;
786  
    }
787  
  }
788  
  
789  
  static boolean validate(String[] example, Learner learner) {
790  
    try {
791  
      String out = (String) learner.processIn(example[0]);
792  
      if (!example[1].equals(out)) {
793  
          //System.out.println("[fail] " + learner + " on " + quote(e[0]) + " - got: " + quote(out) + " rather than: " + quote(e[1]));
794  
          return false;
795  
        }
796  
      return true;
797  
    } catch (Throwable e) {
798  
      silentException(e);
799  
      return false;
800  
    }
801  
  }
802  
  
803  
  static void silentException(Throwable e) {
804  
  }
805  
  
806  
  static List<Learner> makeLearners() ctex {
807  
    new List<Learner> list;
808  
    for (String strategy : strategies) {
809  
      String s = isSnippetID(strategy) ? loadSnippet(strategy) : strategy;
810  
      s += "\n" + combineClasses();
811  
      
812  
      if (printStrategy)
813  
        System.out.println("Strategy:\n" + s);
814  
        
815  
      list.addAll(parseStrategy(s));
816  
      if (classic)
817  
        list.addAll(classicLearners()); // Endlosschleife!?
818  
    }
819  
    return list;
820  
  }
821  
  
822  
  static String[] extensiveLearners = {
823  
    "LFunctionPlusPrevious",
824  
    "LCombineTwoFunctions",
825  
    "LCombineTwoFunctions2"
826  
  };
827  
  
828  
  static List<Class> extensiveLearnerClasses;
829  
  
830  
  static boolean isExtensive(Class c) {
831  
    if (extensiveLearnerClasses == null) {
832  
      extensiveLearnerClasses = new ArrayList<Class>();
833  
      for (String s : extensiveLearners) {
834  
        Class cc = findClassFlex(s);
835  
        if (cc != null)
836  
          extensiveLearnerClasses.add(cc);
837  
      }
838  
    }
839  
    return extensiveLearnerClasses.contains(c);
840  
  };
841  
  
842  
  static boolean extensiveOK(Class c) {
843  
    return extensiveMode || !isExtensive(c);
844  
  }
845  
  
846  
  static String combineClasses() {
847  
    new StringBuilder buf;
848  
    for (String s : innerClasses) {
849  
      Class c = findClass(s);
850  
      if (c == null) System.err.println("Warning: Class not found - " + s);
851  
      else if (isSubclass(c, Learner.class) && extensiveOK(c)) {
852  
        //System.out.println("combineClasses: " + c);
853  
        if (hasConstructor(false, c))
854  
          buf.append(getName(c) + "\n");
855  
        for (String s2 : innerClasses)  {
856  
          Class c2 = findClass(s2);
857  
          if (c2 == null) continue;
858  
          if (!hasConstructor(false, c2)) continue; // no default constructor
859  
          boolean ctr = hasConstructor(false, c, c2);
860  
          /*if (c == LUse.class)
861  
            System.out.println("combineClasses: Checking LUse " + c2+ ", ctr=" + ctr);*/
862  
          if (c2 != null && ctr && extensiveOK(c2))
863  
            buf.append(getName(c) + " " + getName(c2) + "\n");
864  
        }
865  
      }
866  
    }
867  
    return buf.toString();
868  
  }
869  
  
870  
  static List<Learner> parseStrategy(String strategyText) ctex {
871  
    List <String> lines = toLines(strategyText);
872  
    new List<Learner> list;
873  
    for (String s : lines) try {
874  
      s = s.trim();
875  
      String[] parts = s.split(" +");
876  
      if (parts.length == 0) continue;
877  
      
878  
      new Stack<Object> stack;
879  
      for (int i = parts.length-1; i >= 0; i--) {
880  
        String p = parts[i];
881  
        Class c = findClassFlex(p);
882  
        if (c == null)
883  
          fail("Strategy element " + p + " not known");
884  
        
885  
        Constructor ctr = c.getDeclaredConstructors()[0];
886  
        Class[] types = ctr.getParameterTypes();
887  
        if (types.length == 0)
888  
          stack.add(ctr.newInstance());
889  
        else if (types.length == 1) {
890  
          if (stack.isEmpty())
891  
            fail("Too few arguments for " + c.getName());
892  
          stack.add(ctr.newInstance(stack.pop()));
893  
        } else if (types.length == 2) {
894  
          if (stack.size() < 2)
895  
            fail("Too few arguments for " + c.getName());
896  
          Object a = stack.pop();
897  
          Object b = stack.pop();
898  
          stack.add(ctr.newInstance(a, b));
899  
        } else
900  
          fail("bla");
901  
        
902  
        /*if (isSubclass(c, ReversibleFunction.class)) {
903  
          l = new LWrap((ReversibleFunction) newInstance(c), l);
904  
          continue;
905  
        }*/
906  
      }
907  
      
908  
      list.add((Learner) stack.peek());
909  
    } catch (Throwable e) {
910  
      System.err.println("Strategy parse error.");
911  
      e.printStackTrace();
912  
      strategyParseErrors.add(e);
913  
    }
914  
    return list;
915  
  }
916  
917  
  static List<Learner> classicLearners() {
918  
    new List<Learner> list;
919  
    list.addAll(level1());
920  
    list.add(new LBox(new LMulti(level1())));
921  
    list.add(new LBox2(new LMulti(level1())));
922  
    
923  
    list.add(new LChange(new FCommonPrefix(), new LOutPattern()));
924  
    list.add(new LChange(new FCommonSuffix(), new LOutPattern()));
925  
    
926  
    list.add(new LEmptyBox(new LMulti(level1())));
927  
    
928  
    list.add(new LChange(new RFToLines(), new LFixedFunction(new FLength())));
929  
    
930  
    // for #1000455
931  
    list.add(new LFindOutInIn(new LFixedSubstring()));
932  
   
933  
    for (int I = 1; I <= 2; I++)
934  
    // for #1000457
935  
    list.add(new LChange(new FDropFirstLines(I), new LMulti(
936  
      new LFixWhitespace(l1()), level1())));
937  
938  
    // for #1000458
939  
    list.add(new LFixWhitespace(l1()));
940  
941  
    return list;
942  
  }
943  
944  
  static Learner l1() {
945  
    return new LMulti(level1());
946  
  }
947  
  
948  
  static List<Learner> level1() {
949  
    new List<Learner> list;
950  
    list.add(new LId()); // always good to have as included learner
951  
    list.add(new LPrefixSuffix());
952  
    list.add(new LSplitInput(new LOutPattern()));
953  
    list.add(new LInputPattern());
954  
    list.add(new LFixed());
955  
    list.add(new LWrap(new RFJavaTok(), new LEach(new LFixedFunction(new EscapeCase()))));
956  
    list.add(new LCharShift());
957  
    list.add(new LOutSuffix(new LFirst(new LCharShift())));
958  
    
959  
    list.add(new LChange(new RFJavaTok(), new LMulti(
960  
      new LChange(new FStringsOnly(), new LGetListElement()),
961  
      new LChange(new FNumbersOnly(), new LMath()))
962  
    ));
963  
    
964  
    // TODO - for #1000378
965  
    list.add(new LChange(new RFJavaTok(), new LDistinguishList(new FIsString())));
966  
    
967  
    list.add(new LFixedSubstring());
968  
    
969  
    return list;
970  
  }
971  
  
972  
  static String indent(String indent, String s) {
973  
    return indent + s.replace("\n", "\n" + indent);
974  
  }
975  
  
976  
  static void debugOn(String name) {
977  
    try {
978  
      Class c = findClassFlex(name);
979  
      debuggedClasses.add(c);
980  
      Field field;
981  
      while (true)
982  
        try {
983  
          field = c.getDeclaredField("debug");
984  
          break;
985  
        } catch  (NoSuchFieldException e) {
986  
          c = c.getSuperclass();
987  
        }
988  
      field.setBoolean(null, true);
989  
    } catch (Exception e) {
990  
      e.printStackTrace();
991  
      System.err.println("Cannot debug class " + name);
992  
    }
993  
  }
994  
995  
static int choice(String text, int i) {
996  
  return i;
997  
}
998  
  
999  
  // splits the input at some point, takes only one part
1000  
  static class LSplitInput extends LearnerImpl {
1001  
    int splitIdx = 1; // split after first character
1002  
    Learner baseLearner;
1003  
    
1004  
    LSplitInput(Learner baseLearner) {
1005  
      this.baseLearner = baseLearner;
1006  
      splitIdx = choice("LSplitInput.i", splitIdx);
1007  
    }
1008  
    
1009  
    public void processInOut(Object _in, Object _out) {
1010  
      String in = (String) _in, out = (String) _out;
1011  
      in = in.substring(splitIdx);
1012  
      baseLearner.processInOut(in, out);
1013  
    }
1014  
    
1015  
    public Object processIn(Object _in) {
1016  
      String in = (String) _in;
1017  
      in = in.substring(splitIdx);
1018  
      return baseLearner.processIn(in);
1019  
    }
1020  
    
1021  
    public void toJava(Code code) {
1022  
      if (splitIdx != 0)
1023  
        code.line(code.var + " = ((String) " + code.var + ").substring(" + splitIdx + ");");
1024  
      baseLearner.toJava(code);
1025  
    }
1026  
  }
1027  
1028  
  static class FDropFirstLines implements Function {
1029  
    int n;
1030  
    *(int *n) {}
1031  
1032  
    public Object process(Object _in) {
1033  
      String in = (String)_in;
1034  
      for (int I=0; I < n; I++)
1035  
        in = in.substring(in.indexOf('\n')+1);
1036  
      return in;
1037  
    }
1038  
    
1039  
    public void toJava_process(Code code) {
1040  
      todo();
1041  
    }
1042  
  }
1043  
  
1044  
  // removes common suffix from out, delegates to base learner
1045  
  static class LOutSuffix extends LearnerImpl {
1046  
    String suffixOut = "";
1047  
    Learner baseLearner;
1048  
    
1049  
    LOutSuffix(Learner baseLearner) {
1050  
      this.baseLearner = baseLearner;
1051  
    }
1052  
    
1053  
    public void processInOut(Object _in, Object _out) {
1054  
      String in = (String) _in, out = (String) _out;
1055  
      if (out.endsWith("!"))
1056  
        suffixOut = "!";
1057  
      if (out.endsWith(suffixOut))
1058  
        out = out.substring(0, out.length()-suffixOut.length());
1059  
      
1060  
      baseLearner.processInOut(in, out);
1061  
    }
1062  
    
1063  
    public Object processIn(Object _in) {
1064  
      String in = (String) _in;
1065  
      return baseLearner.processIn(in) + suffixOut;
1066  
    }
1067  
    
1068  
    public void toJava(Code code) {
1069  
      baseLearner.toJava(code);
1070  
      if (suffixOut.length() != 0)
1071  
        code.line(code.var + " = " + code.s() + "+" + quote(suffixOut) + ";");
1072  
    }
1073  
  }
1074  
  
1075  
  // if input appears in output in fixed pattern
1076  
  static class LOutPattern extends LearnerImpl {
1077  
    static boolean debug;
1078  
    String pattern = "%!%";
1079  
1080  
    public void processInOut(Object _in, Object _out) {
1081  
      String in = (String) _in, out = (String) _out;
1082  
      pattern = out.replace(in, "%!%");
1083  
      if (debug)
1084  
        System.out.println("LOutPattern: in=" + quote(in) + ", out=" + quote(out) + ", pattern=" + quote(pattern));
1085  
    }
1086  
    
1087  
    public String processIn(Object _in) {
1088  
      String in = (String) _in;
1089  
      return pattern.replace("%!%", in);
1090  
    }
1091  
    
1092  
    public void toJava(Code code) {
1093  
      code.line(code.var + " = " + quote(pattern) + ".replace(" + quote("%!%") + ", (String) " + code.var + ");");
1094  
    }
1095  
  }
1096  
  
1097  
  // simplets learner - only knows the "id" function
1098  
  static class LId extends LearnerImpl {
1099  
    public void processInOut(Object in, Object out) {
1100  
    }
1101  
    
1102  
    public Object processIn(Object in) {
1103  
      return in;
1104  
    }
1105  
    
1106  
    public void toJava(Code code) {
1107  
    }
1108  
  }
1109  
  
1110  
  !include #1000584 // LInputPattern
1111  
  
1112  
  static class LFixed extends LearnerImpl {
1113  
    static boolean debug;
1114  
    Object value;
1115  
    
1116  
    public void processInOut(Object in, Object out) {
1117  
      value = out;
1118  
      if (debug)
1119  
        printVars();
1120  
    }
1121  
    
1122  
    public Object processIn(Object in) {
1123  
      return value;
1124  
    }
1125  
    
1126  
    public void toJava(Code code) {
1127  
      code.line(code.var + " = " + quote((String) value) + ";");
1128  
    }
1129  
  }
1130  
  
1131  
  static void fail() {
1132  
    throw new RuntimeException("fail");
1133  
  }
1134  
  
1135  
  static void fail(String msg) {
1136  
    throw new RuntimeException(msg);
1137  
  }
1138  
  
1139  
  static void assertSameSize(List a, List b) {
1140  
    if (a.size() != b.size())
1141  
      fail("wrong list sizes");
1142  
  }
1143  
1144  
  // process lists in parallel
1145  
  // (in and out must be a list of same length)
1146  
  static class LEach extends LearnerImpl {
1147  
    static boolean debug;
1148  
    Learner base;
1149  
    
1150  
    LEach(Learner base) {
1151  
      this.base = base;
1152  
    }
1153  
    
1154  
    public void processInOut(Object _in, Object _out) {
1155  
      List in = (List) _in, out = (List) _out;
1156  
      assertSameSize(in, out);
1157  
      for (int i = 0; i < in.size(); i++)
1158  
        base.processInOut(in.get(i), out.get(i));
1159  
      if (debug)
1160  
        printVars();
1161  
    }
1162  
    
1163  
    public Object processIn(Object _in) {
1164  
      List in = (List) _in;
1165  
      List out = new ArrayList();
1166  
      for (Object x : in)
1167  
        out.add(base.processIn(x));
1168  
      return out;
1169  
    }
1170  
    
1171  
    public void toJava(Code code) {
1172  
      code.line("List out = new ArrayList();");
1173  
      code.line("for (Object x : (List) in) {");
1174  
      code.indent();
1175  
      code.line("in = x;");
1176  
      base.toJava(code);
1177  
      code.line("out.add(in);");
1178  
      code.unindent();
1179  
      code.line("}");
1180  
      code.line("in = out;");
1181  
    }
1182  
  }
1183  
  
1184  
  static class LChange extends LearnerImpl {
1185  
    Function f;
1186  
    Learner base;
1187  
    
1188  
    LChange(Function f, Learner base) {
1189  
      this.f = f;
1190  
      this.base = base;
1191  
    }
1192  
    
1193  
    public void processInOut(Object in, Object out) {
1194  
      in = f.process(in);
1195  
      base.processInOut(in, out);
1196  
    }
1197  
    
1198  
    public Object processIn(Object in) {
1199  
      in = f.process(in);
1200  
      return base.processIn(in);
1201  
    }
1202  
    
1203  
    public void toJava(Code code) {
1204  
      f.toJava_process(code);
1205  
      base.toJava(code);
1206  
    }
1207  
  }
1208  
  
1209  
  static class LFindOutInIn extends LearnerImpl {
1210  
    static boolean debug;
1211  
    Learner base;
1212  
    String findMarker1 = "{{", findMarker2 = "}}";
1213  
    
1214  
    *(Learner *base) {}
1215  
    
1216  
    public void processInOut(Object _in, Object _out) {
1217  
      String in = (String) _in, out = (String) _out;
1218  
      if (out.length() == 0)
1219  
        out = in;
1220  
      else {
1221  
        int i = in.indexOf(out);
1222  
        if (i < 0) throw new RuntimeException("error");
1223  
        int j = i+out.length();
1224  
        out = in.substring(0, i) + findMarker1 + in.substring(i, j) + findMarker2 + in.substring(j);
1225  
        if (debug)
1226  
          System.out.println("LFindOutInIn: index=" + i);
1227  
      }
1228  
      
1229  
      base.processInOut(in, out);
1230  
      
1231  
      if (debug)
1232  
        System.out.println("LFindOutInIn: Base learned. " + base);
1233  
    }
1234  
    
1235  
    public Object processIn(Object _in) {
1236  
      if (debug)
1237  
        System.out.println("LFindOutInIn: processIn");
1238  
      String in = (String) _in;
1239  
      String out = (String) base.processIn(in);
1240  
      int i = out.indexOf(findMarker1), j = out.indexOf(findMarker2, i)-2;
1241  
      String result = i < 0 ? "" : in.substring(i, j);
1242  
      if (debug)
1243  
        System.out.println("LFindOutInIn: processIn " + i + " " + j + " " + quote(result));
1244  
      return result;
1245  
    }
1246  
    
1247  
    public void tryAgain() {
1248  
      base.tryAgain();
1249  
    }
1250  
  }
1251  
  
1252  
  static class RFJavaTok implements ReversibleFunction {
1253  
    public Object process(Object in) {
1254  
      return JavaTok.split((String) in);
1255  
    }
1256  
    
1257  
    public Object unprocess(Object in) {
1258  
      return join((List) in);
1259  
    }
1260  
    
1261  
    public void toJava_process(Code code) {
1262  
      code.translators("!636", "!class JavaTok");
1263  
      code.line(code.var + " = JavaTok.split((String) " + code.var + ");");
1264  
    }
1265  
    
1266  
    public void toJava_unprocess(Code code) {
1267  
      code.translators("!636", "!class JavaTok");
1268  
      code.line(code.var + " = join((List) " + code.var + ");");
1269  
    }
1270  
  }
1271  
  
1272  
  static class RFToLines implements ReversibleFunction {
1273  
    public Object process(Object in) {
1274  
      return toLines((String) in);
1275  
    }
1276  
    
1277  
    public Object unprocess(Object in) {
1278  
      return fromLines((List) in);
1279  
    }
1280  
    
1281  
    public void toJava_process(Code code) {
1282  
      code.translators("!636", "!standard functions");
1283  
      code.assign("toLines(" + code.s() + ");");
1284  
    }
1285  
    
1286  
    public void toJava_unprocess(Code code) {
1287  
      code.translators("!636", "!standard functions");
1288  
      code.assign("fromLines(" + code.list() + ");");
1289  
    }
1290  
  }
1291  
  
1292  
  // works on a token list - makes a list of only the string constants (unquoted)
1293  
  static class FStringsOnly implements Function {
1294  
    static boolean debug;
1295  
    
1296  
    public Object process(Object _in) {
1297  
      new List<String> tok;
1298  
      for (String s : (List<String>) _in) {
1299  
        boolean isString = s.startsWith("\"") || s.startsWith("[[");
1300  
        if (isString)
1301  
          tok.add(unquote(s));
1302  
        if (debug)
1303  
          System.out.println("FStringsOnly - isString: " + isString + " - " + s);
1304  
      }
1305  
      return tok;
1306  
    }
1307  
    
1308  
    public void toJava_process(Code code) {
1309  
      code.translators("!standard functions");
1310  
      code.line("List<String> tok = new ArrayList<String>();");
1311  
      code.line("for (String s : (List<String>) " + code.var + ")");
1312  
      code.line("  if (s.startsWith(\"\\\"\") || s.startsWith(\"[[\")) tok.add(unquote(s));");
1313  
      code.assign("tok");
1314  
    }
1315  
  }
1316  
  
1317  
  // works on a token list - makes a list of only the number constants
1318  
  static class FNumbersOnly implements Function {
1319  
    static boolean debug;
1320  
    
1321  
    public Object process(Object _in) {
1322  
      new List<String> tok;
1323  
      for (String s : (List<String>) _in) {
1324  
        boolean isNumber = s.length() != 0 && (Character.isDigit(s.charAt(0)) || (s.charAt(0) == '-' && s.length() > 1));
1325  
        if (isNumber)
1326  
          tok.add(s);
1327  
        if (debug)
1328  
          System.out.println("FNumbersOnly - isNumber: " + isNumber + " - " + s);
1329  
      }
1330  
      return tok;
1331  
    }
1332  
    
1333  
    public void toJava_process(Code code) {
1334  
      code.line("List<String> tok = new ArrayList<String>();");
1335  
      code.line("for (String s : (List<String>) " + code.var + ")");
1336  
      code.line("  if (s.length() != 0 && (Character.isDigit(s.charAt(0)) || (s.charAt(0) == '-' && s.length() > 1))) tok.add(s);");
1337  
      code.assign("tok");
1338  
    }
1339  
  }
1340  
  
1341  
  static class FLength implements Function {
1342  
    static boolean debug;
1343  
    
1344  
    public Object process(Object in) {
1345  
      Object result = String.valueOf(in instanceof List ? ((List) in).size() : ((String) in).length());
1346  
      if (debug)
1347  
        System.out.println("FLength: " + result);
1348  
      return result;
1349  
    }
1350  
    
1351  
    public void toJava_process(Code code) {
1352  
      code.assign("String.valueOf(" + code.var + " instanceof List ? " + code.list() + ".size() : " + code.s() + ".length())");
1353  
    }
1354  
  }
1355  
  
1356  
  static class LFixedFunction extends LearnerImpl {
1357  
    Function f;
1358  
    
1359  
    LFixedFunction(Function f) {
1360  
      this.f = f;
1361  
    }
1362  
    
1363  
    public void processInOut(Object in, Object out) {
1364  
    }
1365  
    
1366  
    public Object processIn(Object in) {
1367  
      return f.process(in);
1368  
    }
1369  
    
1370  
    public void toJava(Code code) {
1371  
      f.toJava_process(code);
1372  
    }
1373  
  }
1374  
  
1375  
  // trivial stuff like taking the one element out of a 1-element list
1376  
  static class LTrivial extends LearnerImpl {
1377  
    public void processInOut(Object in, Object out) {
1378  
    }
1379  
    
1380  
    public Object processIn(Object in) {
1381  
      return ((List) in).get(0);
1382  
    }
1383  
    
1384  
    public void toJava(Code code) {
1385  
      code.assign(code.list() + ".get(0)");
1386  
    }
1387  
  }
1388  
  
1389  
  // get element of a list at fixed index
1390  
  static class LGetListElement extends LearnerImpl {
1391  
    static boolean debug;
1392  
    int i;
1393  
    
1394  
    public void processInOut(Object _in, Object out) {
1395  
      List in = (List) _in;
1396  
      i = in.indexOf(out);
1397  
      if (debug)
1398  
        System.out.println("LGetListElement: " + i + " " + out);
1399  
    }
1400  
    
1401  
    public Object processIn(Object in) {
1402  
      return ((List) in).get(i);
1403  
    }
1404  
    
1405  
    public void toJava(Code code) {
1406  
      code.assign(code.list() + ".get(" + i + ")");
1407  
    }
1408  
  }
1409  
  
1410  
  // math operations
1411  
  static class LMath extends LearnerImpl {
1412  
    static boolean debug;
1413  
    String allOperations = "+ - * /";
1414  
    new (Tree)Set<String> possibleOperations;
1415  
    
1416  
    LMath() {
1417  
      possibleOperations.addAll(Arrays.asList(allOperations.split(" +")));
1418  
    }
1419  
    
1420  
    public void processInOut(Object _in, Object _out) {
1421  
      List in = (List) _in;
1422  
      String out = (String) _out;
1423  
      BigInteger[] inNumbers = getNumbers(in);
1424  
      BigInteger[] outNumbers = new BigInteger[] {getNumber(out)};
1425  
      findOperation(inNumbers, outNumbers);
1426  
      if (debug)
1427  
        System.out.println("Operations: " + possibleOperations);
1428  
    }
1429  
    
1430  
    public void findOperation(BigInteger[] in, BigInteger[] out) {
1431  
      filterOperations(in, out);
1432  
      if (possibleOperations.isEmpty())
1433  
        fail("tilt");
1434  
    }
1435  
      
1436  
    public void filterOperations(BigInteger[] in, BigInteger[] out) {
1437  
      for (Iterator<String> i = possibleOperations.iterator(); i.hasNext(); ) {
1438  
        String op = i.next();
1439  
        BigInteger[] out2 = doOperation(op, in);
1440  
        if (out2 == null || !arraysEqual(out, out2))
1441  
          i.remove(); // keep only matching operations
1442  
      }
1443  
    }
1444  
    
1445  
    public BigInteger[] doOperation(String op, BigInteger[] in) {
1446  
      op = op.intern();
1447  
      try {
1448  
        if (in.length == 2) {
1449  
          BigInteger a = in[0], b = in[1], x = null;
1450  
          if (op == "+")
1451  
            x = a.add(b);
1452  
          else if (op == "-")
1453  
            x = a.subtract(b);
1454  
          else if (op == "*")
1455  
            x = a.multiply(b);
1456  
          else if (op == "/")
1457  
            x = a.divide(b);
1458  
          return x != null ? new BigInteger[] {x} : null;
1459  
        }
1460  
        return null;
1461  
      } catch (Throwable e) {
1462  
        return null;
1463  
      }
1464  
    }
1465  
    
1466  
    public String processIn(Object _in) {
1467  
      List<String> in = (List<String>) _in;
1468  
      String op = possibleOperations.iterator().next();
1469  
      if (debug)
1470  
        System.out.println("op: " + op);
1471  
      BigInteger[] inNumbers = getNumbers(in);
1472  
      BigInteger[] outNumbers = doOperation(op, inNumbers);
1473  
      return outNumbers[0].toString();
1474  
    }
1475  
    
1476  
    String BI = BigInteger.class.getName();
1477  
    
1478  
    public void toJava(Code code) {
1479  
      String op = possibleOperations.iterator().next();
1480  
      String a = "new " + BI + "((String) " + code.list() + ".get(0))";
1481  
      String b = "new " + BI + "((String) " + code.list() + ".get(1))";
1482  
      if (op.equals("+"))
1483  
        code.assign(a + ".add(" + b + ").toString()");
1484  
      else
1485  
        todo();
1486  
    }
1487  
    
1488  
    static BigInteger[] getNumbers(List<String> in) {
1489  
      BigInteger[] big = new BigInteger[in.size()];
1490  
      for (int i = 0; i < in.size(); i++)
1491  
        big[i] = new BigInteger(in.get(i));
1492  
      return big;
1493  
    }
1494  
    
1495  
    static BigInteger getNumber(String s) {
1496  
      return new BigInteger(s);
1497  
    }
1498  
    
1499  
    static boolean arraysEqual(BigInteger[] a, BigInteger[] b) {
1500  
      if (a.length != b.length) return false;
1501  
      for (int i = 0; i < a.length; i++)
1502  
        if (!a[i].equals(b[i])) return false;
1503  
      return true;
1504  
    }
1505  
  }
1506  
  
1507  
  static class EscapeCase implements Function {
1508  
    static boolean debug;
1509  
    
1510  
    public Object process(Object _in) {
1511  
      if (debug)
1512  
        System.out.println("EscapeCase: " + _in);
1513  
      String in = (String) _in;
1514  
      return in.equals("case") ? "_case" : in;
1515  
    }
1516  
    
1517  
    public void toJava_process(Code code) {
1518  
      code.line("if (\"case\".equals(" + code.var + ")) " + code.var + " = " + quote("_case") + ";");
1519  
    }
1520  
  }
1521  
  
1522  
  static class LCharShift extends LearnerImpl {
1523  
    int shift;
1524  
    
1525  
    public void processInOut(Object _in, Object _out) {
1526  
      String in = (String) _in, out = (String) _out;
1527  
      shift = (int) out.charAt(0) - (int) in.charAt(0);
1528  
    }
1529  
    
1530  
    public Object processIn(Object _in) {
1531  
      String in = (String) _in;
1532  
      char[] c = new char[in.length()];
1533  
      for (int i = 0; i < c.length; i++)
1534  
        c[i] = (char) ((int) in.charAt(i) + shift);
1535  
      return new String(c);
1536  
    }
1537  
    
1538  
    public void toJava(Code code) {
1539  
      code.line("char[] c = new char[((String) " + code.var + ").length()];");
1540  
      code.line("for (int i = 0; i < c.length; i++)");
1541  
      code.line("  c[i] = (char) ((int) ((String) " + code.var + ").charAt(i)" + (shift < 0 ? "" + shift : "+" + shift) + ");");
1542  
      code.line(code.var + " = new String(c);");
1543  
    }
1544  
  }
1545  
  
1546  
  // applies base learner to first char of string
1547  
  // (or first element of list, TODO)
1548  
  static class LFirst extends LearnerImpl {
1549  
    Learner baseLearner;
1550  
    
1551  
    *(Learner baseLearner) {
1552  
      this.baseLearner = baseLearner;
1553  
    }
1554  
    
1555  
    public void processInOut(Object _in, Object _out) {
1556  
      String in = (String) _in, out = (String) _out;
1557  
      if (in.length() == 0)
1558  
        return;
1559  
      String firstIn = in.substring(0, 1), firstOut = out.substring(0, 1);
1560  
      baseLearner.processInOut(firstIn, firstOut);
1561  
    }
1562  
    
1563  
    public Object processIn(Object _in) {
1564  
      String in = (String) _in;
1565  
      if (in.length() == 0)
1566  
        return in;
1567  
      String firstIn = in.substring(0, 1);
1568  
      return baseLearner.processIn(firstIn) + in.substring(1);
1569  
    }
1570  
    
1571  
    public void toJava(Code code) {
1572  
      code.line("if (" + code.s() + ".length() != 0) {");
1573  
      code.indent();
1574  
      code.line("String rest = " + code.s() + ".substring(1);");
1575  
      code.line(code.var + " = " + code.s() + ".substring(0, 1);");
1576  
      baseLearner.toJava(code);
1577  
      code.line(code.var + " = " + code.s() + "+rest;");
1578  
      code.unindent();
1579  
      code.line("}");
1580  
    }
1581  
  }
1582  
  
1583  
  static Method findMainMethod(Class<?> theClass) {
1584  
    for (Method method : theClass.getMethods())
1585  
      if (method.getName().equals("main") && method.getParameterTypes().length == 1)
1586  
        return method;
1587  
    throw new RuntimeException("Method 'main' with 1 parameter not found in " + theClass.getName());
1588  
  }
1589  
  
1590  
  // compile JavaX source and load main class
1591  
  static Class<?> compileAndLoadMainClass(String src) throws Exception {
1592  
    File srcDir = _x18.TempDirMaker_make();
1593  
    File classesDir = _x18.TempDirMaker_make();
1594  
    _x18.saveTextFile(new File(srcDir, "main.java").getPath(), src);
1595  
    new List<File> libraries;
1596  
    File transpiledDir = _x18.topLevelTranslate(srcDir, libraries);
1597  
    String javacOutput = _x18.compileJava(transpiledDir, libraries, classesDir);
1598  
    System.out.println(javacOutput);
1599  
    URL[] urls = {classesDir.toURI().toURL()};
1600  
    
1601  
    // make class loader
1602  
    URLClassLoader classLoader = new URLClassLoader(urls);
1603  
1604  
    // load main class
1605  
    Class<?> mainClass = classLoader.loadClass("main");
1606  
    return mainClass;
1607  
  }
1608  
      
1609  
  static Method compileJavaInToOut(Code code) {
1610  
    try {
1611  
      String java = code.buf.toString();
1612  
      String prelude = /*"import java.util.*;\n\n" +*/
1613  
        "public class main { public static Object main(Object in) throws Exception {\n";
1614  
      String postlude = "\nreturn in;\n}}";
1615  
      String src = code.getTranslators() + "\n" + prelude + java + postlude;
1616  
      Class<?> mainClass = compileAndLoadMainClass(src);
1617  
      return findMainMethod(mainClass);
1618  
    } catch (Exception e) {
1619  
      throw new RuntimeException(e);
1620  
    }
1621  
  }
1622  
  
1623  
  static Method findCalcMethod(Class<?> theClass) {
1624  
    for (Method method : theClass.getMethods())
1625  
      if (method.getName().equals("calc"))
1626  
        return method;
1627  
    throw new RuntimeException("Method 'calc' not found in " + theClass.getName());
1628  
  }
1629  
  
1630  
  // for simplejava stuff (execute tasks)
1631  
  static String execute(String src) {
1632  
    try {
1633  
      Class<?> mainClass = compileAndLoadMainClass(src);
1634  
      Method m = findCalcMethod(mainClass);
1635  
      return String.valueOf(m.invoke(null));
1636  
    } catch (Exception e) {
1637  
      throw new RuntimeException(e);
1638  
    }
1639  
  }
1640  
  
1641  
  static void testJava(Case case, Code code) {
1642  
    try {
1643  
      Method m = compileJavaInToOut(code);
1644  
      
1645  
      for (Object[] e : case.fullExamples) {
1646  
        String out = (String) m.invoke(null, e[0]);
1647  
        
1648  
        if (!e[1].equals(out)) {
1649  
          throw new RuntimeException("[fail] Java code on " + structure(e[0]) + " - got: " + structure(out) + " rather than: " + structure(e[1]));
1650  
        }
1651  
      }
1652  
      
1653  
      System.out.println("\nGOOD JAVA.");
1654  
      case.goodJava = true;
1655  
    } catch (Throwable e) {
1656  
      if (showFails)
1657  
        e.printStackTrace();
1658  
      System.out.println("\nBAD JAVA.");
1659  
    }
1660  
  }
1661  
  
1662  
  static void todo() {
1663  
    fail("todo");
1664  
  }
1665  
  
1666  
  static class LSwitch extends LearnerImpl {
1667  
    Case case;
1668  
    Learner switcher;
1669  
    
1670  
    *(Case case, Learner switcher) {
1671  
      this.case = case;
1672  
      this.switcher = switcher;
1673  
    }
1674  
    
1675  
    public void processInOut(Object in, Object out) {
1676  
    }
1677  
   
1678  
    public Object processIn(Object in) {
1679  
      int i = Integer.parseInt((String) switcher.processIn(in));
1680  
      return case.combined.get(i-1).winner.processIn(in);
1681  
    }
1682  
   
1683  
    public void toJava(Code code) {
1684  
      todo();
1685  
    }
1686  
  }
1687  
 
1688  
  static class LMulti extends LearnerImpl {
1689  
    static boolean debug;
1690  
    new List<Learner> candidates;
1691  
    
1692  
    *(Learner... learners) {
1693  
      for (Learner l : learners)
1694  
        candidates.add(l);
1695  
    }
1696  
    
1697  
    *(L<Learner> learners) {
1698  
      for (Learner l : learners)
1699  
        candidates.add(l);
1700  
    }
1701  
1702  
    *(Learner l, L<Learner> ll) {
1703  
       candidates.add(l);
1704  
      candidates.addAll(ll);
1705  
    }
1706  
    
1707  
    public void processInOut(Object in, Object out) {
1708  
      if (debug)
1709  
        System.err.println("LMulti candidates: " + candidates.size());
1710  
      for (ListIterator<Learner> i = candidates.listIterator(); i.hasNext(); ) {
1711  
        Learner l = i.next();
1712  
        try {
1713  
          l.processInOut(in, out);
1714  
        } catch (Throwable e) {
1715  
          if (debug) {
1716  
            e.printStackTrace();
1717  
            System.err.println("Removing candidate: " + structure(l));
1718  
          }
1719  
          silentException(e);
1720  
          i.remove();
1721  
        }
1722  
      }
1723  
      if (debug)
1724  
        System.err.println("LMulti candidates now: " + candidates.size());
1725  
      if (candidates.isEmpty())
1726  
        fail("no candidates left");
1727  
    }
1728  
    
1729  
    public Object processIn(Object in) {
1730  
      while (true) { // fails or returns eventually
1731  
        Learner l = candidates.get(0);
1732  
        if (debug)
1733  
          System.err.println("Using candidate: " + structure(l) + ", " + candidates.size() + " left");
1734  
        try {
1735  
          return l.processIn(in);
1736  
        } catch (Throwable e) {
1737  
          if (debug) {
1738  
            e.printStackTrace();
1739  
            System.err.println("Removing candidate: " + structure(l));
1740  
          }
1741  
          silentException(e);
1742  
          candidates.remove(0);
1743  
        }
1744  
      }
1745  
    }
1746  
    
1747  
    public void tryAgain() {
1748  
      candidates.remove(0);
1749  
    }
1750  
    
1751  
    public void toJava(Code code) {
1752  
      candidates.get(0).toJava(code);
1753  
    }
1754  
  }
1755  
  
1756  
  static String structure(Object o) {
1757  
    return structure(o, 0);
1758  
  }
1759  
  
1760  
  static String structure(Object o, int stringSizeLimit) {
1761  
    if (o == null) return "null";
1762  
    String name = o.getClass().getName();
1763  
    
1764  
    new StringBuilder buf;
1765  
    
1766  
    if (o instanceof Collection) {
1767  
      for (Object x : (Collection) o) {
1768  
        if (!buf.isEmpty()) buf.append(", ");
1769  
        buf.append(structure(x, stringSizeLimit));
1770  
      }
1771  
      return "{" + buf + "}";
1772  
    }
1773  
    
1774  
    if (o.getClass().isArray()) {
1775  
      int n = Array.getLength(o);
1776  
      for (int i = 0; i < n; i++) {
1777  
        if (!buf.isEmpty()) buf.append(", ");
1778  
        buf.append(structure(Array.get(o, i), stringSizeLimit));
1779  
      }
1780  
      return "{" + buf + "}";
1781  
    }
1782  
1783  
    if (o instanceof String)
1784  
      return quote(stringSizeLimit != 0 ? shorten((String) o, stringSizeLimit) : (String) o);
1785  
    
1786  
    // Need more cases? This should cover all library classes...
1787  
    if (name.startsWith("java.") || name.startsWith("javax."))
1788  
      return String.valueOf(o);
1789  
      
1790  
    String shortName = o.getClass().getName().replaceAll("^main\\$", "");
1791  
1792  
    // TODO: go to superclasses too
1793  
    Field[] fields = o.getClass().getDeclaredFields();
1794  
    int numFields = 0;
1795  
    String fieldName = "";
1796  
    for (Field field : fields) {
1797  
      if ((field.getModifiers() & Modifier.STATIC) != 0)
1798  
        continue;
1799  
      Object value;
1800  
      try {
1801  
        value = field.get(o);
1802  
      } catch (Exception e) {
1803  
        value = "?";
1804  
      }
1805  
      
1806  
      fieldName = field.getName();
1807  
      
1808  
      // special case for LMulti - show only first (current) candidate
1809  
      if (shortName.equals("LMulti") && field.getName().equals("candidates")) {
1810  
        fieldName = "candidate";
1811  
        value = getFirst(value);
1812  
      }
1813  
        
1814  
      // same for functions list in steppers
1815  
      if (shortName.equals("LCombineTwoFunctions2$Stepper") && field.getName().equals("functions") && value instanceof List) {
1816  
        int i1 = (Integer) get(o, "i1"), i2 = (Integer) get(o, "i2");
1817  
        value = new Object[] {((List) value).get(i1), ((List) value).get(i2)};
1818  
      }
1819  
        
1820  
      if (value != null) {
1821  
        if (!buf.isEmpty()) buf.append(", ");
1822  
        buf.append(fieldName + "=" + structure(value, stringSizeLimit));
1823  
      }
1824  
      ++numFields;
1825  
    }
1826  
    String b = buf.toString();
1827  
    if (numFields == 1)
1828  
      b = b.replaceAll("^" + fieldName + "=", ""); // drop field name if only one
1829  
    String s = shortName;
1830  
    if (!buf.isEmpty())
1831  
      s += "(" + b + ")";
1832  
    return s;
1833  
  }
1834  
  
1835  
  static class FIsString implements Function {
1836  
    static boolean debug;
1837  
    
1838  
    public Object process(Object _in) {
1839  
      String in = (String) _in;
1840  
      return in.startsWith("\"") || in.startsWith("[[") ? "1" : "0";
1841  
    }
1842  
    
1843  
    public void toJava_process(Code code) {
1844  
      code.assign(code.s() + ".startsWith(\"\\\"\") || " + code.s() + ".startsWith(\"[[\") ? \"1\" : \"0\"");
1845  
    }
1846  
  }
1847  
  
1848  
  static class FCommonPrefix implements Function {
1849  
    static boolean debug;
1850  
1851  
    public Object process(Object _in) {
1852  
      String in = (String) _in, prefix = null;
1853  
      for (String line : toLines(in))
1854  
        if (line.length() != 0) {
1855  
          prefix = prefix == null ? line : commonPrefix(prefix, line);
1856  
          if (debug)
1857  
            System.out.println("FCommonPrefix: line=" + quote(line) + ", prefix=" + quote(prefix));
1858  
        }
1859  
      return prefix;
1860  
    }
1861  
    
1862  
    public void toJava_process(Code code) {
1863  
      todo();
1864  
    }
1865  
  }
1866  
  
1867  
  static class FCommonSuffix implements Function {
1868  
    static boolean debug;
1869  
1870  
    public Object process(Object _in) {
1871  
      String in = (String) _in, suffix = null;
1872  
      for (String line : toLines(in))
1873  
        if (line.length() != 0) {
1874  
          suffix = suffix == null ? line : commonSuffix(suffix, line);
1875  
          if (debug)
1876  
            System.out.println("FCommonSuffix: line=" + quote(line) + ", suffix=" + quote(suffix));
1877  
        }
1878  
      return suffix;
1879  
    }
1880  
    
1881  
    public void toJava_process(Code code) {
1882  
      todo();
1883  
    }
1884  
  }
1885  
  
1886  
  /*static class Pair {
1887  
    Object a, b;
1888  
    
1889  
    public boolean equals(Object o) {
1890  
      return o instanceof Pair && a.equals(((Pair) o).a) && b.equals((Pair) o).b);
1891  
    }
1892  
    
1893  
    public int hashCode() {
1894  
      return a.hashCode()+b.hashCode()*2;
1895  
    }
1896  
  }*/
1897  
  
1898  
  static class Matrix {
1899  
    new HashMap<Object, Map> dataByCol;
1900  
    
1901  
    void put(Object col, Object row, Object value) {
1902  
      //data.put(new Pair(col, row), value);
1903  
      getCol(col).put(row, value);
1904  
    }
1905  
    
1906  
    Map getCol(Object col) {
1907  
      Map map = dataByCol.get(col);
1908  
      if (map == null)
1909  
        dataByCol.put(col, map = new HashMap());
1910  
      return map;
1911  
    }
1912  
    
1913  
    Object get(Object col, Object row) {
1914  
      //return data.get(new Pair(col, row));
1915  
      return getCol(col).get(row);
1916  
    }
1917  
    
1918  
    Set cols() {
1919  
      return dataByCol.keySet();
1920  
    }
1921  
    
1922  
    Set rowsFor(Object col) {
1923  
      return getCol(col).keySet();
1924  
    }
1925  
  }
1926  
  
1927  
  static class LDistinguishList extends LearnerImpl {
1928  
    static boolean debug;
1929  
    Function helper;
1930  
    int idx;
1931  
    new Matrix matrix;
1932  
1933  
    *(Function helper) {
1934  
      this.helper = helper;
1935  
    }
1936  
    
1937  
    public void processInOut(Object _in, Object out) {
1938  
      List in = (List) _in;
1939  
      for (int i = 0; i < in.size(); i++) {
1940  
        Object y = helper.process(in.get(i));
1941  
        matrix.put(i, y, out);
1942  
      }
1943  
    }
1944  
    
1945  
    public Object processIn(Object _in) {
1946  
      // find idx
1947  
      
1948  
      for (Object i : matrix.cols()) {
1949  
        Collection ys = matrix.rowsFor(i);
1950  
        if (ys.size() > 1) {
1951  
          idx = (Integer) i;
1952  
          break;
1953  
        }
1954  
      }
1955  
      
1956  
      List in = (List) _in;
1957  
      Object y = helper.process(in.get(idx));
1958  
      return matrix.get(idx, y);
1959  
    }
1960  
    
1961  
    public void toJava(Code code) {
1962  
      List ys = new ArrayList(matrix.rowsFor(idx));
1963  
      //String v = code.var;
1964  
      //code.newVar();
1965  
      //String vy = code.var;
1966  
      //code.oldVar();
1967  
      code.assign(code.list() + ".get(" + idx + ")");
1968  
      helper.toJava_process(code);
1969  
      
1970  
      for (int i = 0; i < ys.size(); i++) {
1971  
        Object y = ys.get(i);
1972  
        if (i < ys.size())
1973  
          code.line((i == 0 ? "" : "else ") + "if (" + quote((String) y) + ".equals(" + code.var + "))");
1974  
        else
1975  
          code.line("else");
1976  
        code.line("  " + code.var + " = " + quote((String) matrix.get(idx, y)) + ";");
1977  
      }
1978  
    }
1979  
  }
1980  
  
1981  
  static class RunnersUp {
1982  
    String expected;
1983  
    int bestScore = -1;
1984  
    String bestResult;
1985  
    Learner winner;
1986  
    
1987  
    void add(String expected, String result, int score, Learner learner) {
1988  
      if (!expected.equals(this.expected) || bestScore == -1 || score < bestScore) {
1989  
        bestScore = score;
1990  
        bestResult = result;
1991  
        winner = learner;
1992  
      }
1993  
      this.expected = expected;
1994  
    }
1995  
  }
1996  
  
1997  
  static List<Case> casesSortedByID() {
1998  
    new (Tree)Map<Long, Case> map;
1999  
    new List<Case> rest;
2000  
    for (Case c : cases)
2001  
      if (isSnippetID(c.id))
2002  
        map.put(parseSnippetID(c.id), c);
2003  
      else
2004  
        rest.add(c);
2005  
    List<Case> list = new ArrayList<Case>(map.values());
2006  
    list.addAll(rest);
2007  
    return list;
2008  
  }
2009  
  
2010  
  !include #1000388 // leven (Levenshtein distance function)
2011  
  
2012  
  !include #1000382 // Box learners
2013  
  !include #1000387 // Empty box learner
2014  
  
2015  
  // for "find" tasks (e.g. "abcde" to "[[abc]]de")
2016  
  static class LFixedSubstring extends LearnerImpl {
2017  
    static boolean debug;
2018  
    String findMarker1 = "{{", findMarker2 = "}}";
2019  
    int i, j;
2020  
    
2021  
    public void processInOut(Object _in, Object _out) {
2022  
      String in = (String) _in, out = (String) _out;
2023  
      i = out.indexOf(findMarker1);
2024  
      j = out.indexOf(findMarker2, i)-2;
2025  
      if (debug && j >= 0) {
2026  
        boolean correct = in.substring(i, j).equals(out.substring(i+2, j+2));
2027  
        System.out.println("LFixedSubstring: i, j = " + i + ", " + j + " " + correct + " " + quote(in.substring(i, j)));
2028  
      }
2029  
    }
2030  
    
2031  
    public String processIn(Object _in) {
2032  
      String in = (String) _in;
2033  
      return in.substring(0, i) + findMarker1 + in.substring(i, j) + findMarker2 + in.substring(j);
2034  
    }
2035  
  }
2036  
2037  
  static void print(Object o) {
2038  
    System.out.println(o);
2039  
  }
2040  
2041  
  !include #1000459 // LFixWhiteSpace
2042  
2043  
  static Object newInstance(Class c, Object... args) ctex {
2044  
    Constructor m = findConstructor(c, args);
2045  
    m.setAccessible(true);
2046  
    return m.newInstance(args);
2047  
  }
2048  
  
2049  
  static boolean hasConstructor(boolean debug, Class c, Class... args) {
2050  
    for (Constructor m : c.getDeclaredConstructors()) {
2051  
      if (!checkArgs(m.getParameterTypes(), args, debug))
2052  
        continue;
2053  
      return true;
2054  
    }
2055  
    return false;
2056  
  }
2057  
  
2058  
  static boolean hasConstructor(boolean debug, Class c, Object... args) {
2059  
    for (Constructor m : c.getDeclaredConstructors()) {
2060  
      if (!checkArgs(m.getParameterTypes(), args, debug))
2061  
        continue;
2062  
      return true;
2063  
    }
2064  
    return false;
2065  
  }
2066  
  
2067  
  static Constructor findConstructor(Class c, Object... args) {
2068  
    for (Constructor m : c.getDeclaredConstructors()) {
2069  
      if (!checkArgs(m.getParameterTypes(), args, false))
2070  
        continue;
2071  
      return m;
2072  
    }
2073  
    throw new RuntimeException("Constructor with " + args.length + " matching parameter(s) not found in " + c.getName());
2074  
  }
2075  
  
2076  
  static Class findClass(String name) {
2077  
    for (String c : innerClasses)
2078  
      if (c.equalsIgnoreCase(name))
2079  
        try {
2080  
          return Class.forName("main$" + c);
2081  
        } catch (ClassNotFoundException e) {
2082  
          return null;
2083  
        }
2084  
    return null;
2085  
  }
2086  
  
2087  
  static boolean isSubclass(Class a, Class b) {
2088  
    return b.isAssignableFrom(a);
2089  
  }
2090  
  
2091  
  static boolean checkArgs(Class[] types, Object[] args, boolean debug) {
2092  
    if (types.length != args.length) {
2093  
      if (debug)
2094  
        System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
2095  
      return false;
2096  
    }
2097  
    for (int i = 0; i < types.length; i++)
2098  
      if (!(args[i] == null || types[i].isInstance(args[i]))) {
2099  
        if (debug)
2100  
          System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
2101  
        return false;
2102  
      }
2103  
    return true;
2104  
  }
2105  
  
2106  
  static boolean checkArgs(Class[] types, Class[] args, boolean debug) {
2107  
    if (types.length != args.length) {
2108  
      if (debug)
2109  
        System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
2110  
      return false;
2111  
    }
2112  
    for (int i = 0; i < types.length; i++)
2113  
      if (!(args[i] == null || isSubclass(args[i], types[i]))) {
2114  
        if (debug)
2115  
          System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
2116  
        return false;
2117  
      }
2118  
    return true;
2119  
  }
2120  
  
2121  
  !include #1000465 // LCertainElement
2122  
  
2123  
  static Class findClassFlex(String p) {
2124  
    Class c = findClass(p);
2125  
    if (c == null) c = findClass("L" + p);
2126  
    if (c == null) c = findClass("F" + p);
2127  
    if (c == null) c = findClass("RF" + p);
2128  
    return c;
2129  
  }
2130  
  
2131  
  !include #1000468 // LOneWordChanged
2132  
  !include #1000470 // LBla
2133  
  
2134  
  static String shorten(String s, int max) {
2135  
    return s.length() <= max ? s : s.substring(0, Math.min(s.length(), max)) + "...";
2136  
  }
2137  
  
2138  
  !include #1000481 // LIntersperse
2139  
  
2140  
  static String getName(Class c) {
2141  
    return c.getName().replaceAll("^main\\$", "");
2142  
  }
2143  
  
2144  
  static void keepAlive() {
2145  
    daemon {
2146  
      Object printed = null;
2147  
      while (true) {
2148  
        Object t = trying;
2149  
        Thread.sleep(1000);
2150  
        if (t != null && (verboseMonitor || (t == trying && printed != t))) { // still trying
2151  
          System.err.println("* "+ shorten(structure(t), 200));
2152  
          printed = t;
2153  
        } else printed = null;
2154  
      }
2155  
    }
2156  
  }
2157  
  
2158  
  !include #1000485 // LFixedPositions
2159  
  !include #1000486 // LMap
2160  
  !include #1000492 // LPrefixSuffix
2161  
  !include #1000493 // LRemoveInputSuffix
2162  
  
2163  
  static <T> T overwrite(T existing, T newValue) {
2164  
    if (existing != null && !existing.equals(newValue))
2165  
      fail("Overwrite");
2166  
    return newValue;
2167  
  }
2168  
  
2169  
  static void getPass() ctex {
2170  
    if (user != null) {
2171  
      File pwFile = new File(_x18.userHome(), ".javax/pw-" + user);
2172  
      if (pass == null) {
2173  
        List<String> lines = toLines(readTextFile(pwFile, ""));
2174  
        if (!lines.isEmpty())
2175  
          pass = lines.get(0).trim();
2176  
        if ("".equals(pass)) pass = null;
2177  
        //System.out.println("Pass: " + quote(pass));
2178  
        if (pass != null)
2179  
          System.out.println("Password read from " + pwFile.getAbsolutePath());
2180  
      }
2181  
      if (pass == null)
2182  
        System.out.println("You can put your password in: " + pwFile.getAbsolutePath());
2183  
    }
2184  
  }
2185  
  
2186  
  static void editSnippetText(String docID, String newText, String editInfo) ctex {
2187  
    getPass();
2188  
    System.out.println("Editing " + docID);
2189  
    URL url = new URL("http://tinybrain.de:8080/tb-int/auto-edit.php");
2190  
    String postData =
2191  
        "user=" + urlencode(user)
2192  
      + "&pass=" + urlencode(pass)
2193  
      + "&id=" + urlencode(docID)
2194  
      + "&text=" + urlencode(newText)
2195  
      + "&editinfo=" + urlencode(editInfo);
2196  
    System.out.println(postData);
2197  
    String result = doPost(postData, url.openConnection(), url);
2198  
    System.out.println("Edit result: " + result);
2199  
  }
2200  
  
2201  
  static String urlencode(String s) ctex {
2202  
    return URLEncoder.encode(unnull(s), "UTF-8");
2203  
  }
2204  
  
2205  
  static String doPost(String urlParameters, URLConnection conn, URL url) throws IOException {
2206  
    // connect and do POST
2207  
    conn.setDoOutput(true);
2208  
2209  
    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
2210  
    writer.write(urlParameters);
2211  
    writer.flush();
2212  
2213  
    String contents = loadPage(conn, url);
2214  
    writer.close();
2215  
    return contents;
2216  
  }
2217  
  
2218  
  !include #1000498 // FBeforeColon
2219  
  !include #1000505 // FAfterColon
2220  
  !include #1000499 // FUnquote
2221  
  !include #1000500 // LCombineTwoFunctions
2222  
  !include #1000506 // LCombineTwoFunctions2
2223  
  
2224  
  static List<Function> allFunctions() {
2225  
    new List<Function> list;
2226  
    for (String s : innerClasses) {
2227  
      Class c = findClass(s);
2228  
      if (c == null) continue;
2229  
      if (isSubclass(c, Function.class) && hasConstructor(false, c)) {
2230  
        //System.out.println("allFunctions: " + c);
2231  
        list.add((Function) newInstance(c));
2232  
      }
2233  
    }
2234  
    return list;
2235  
  }
2236  
  
2237  
  static List<Case> solvedCases() {
2238  
    new List<Case> list;
2239  
    for (int i = caseIdx-1; i >= 0; i--)
2240  
      if (cases.get(i).winner != null)
2241  
        list.add(cases.get(i));
2242  
    return list;
2243  
  }
2244  
  
2245  
  static O tryProcess(F f, O in) null on exception {
2246  
    ret f.process(in);
2247  
  }
2248  
  
2249  
  static O tryProcess(Learner l, Object in) null on exception {
2250  
    return l.processIn(in);
2251  
  }  
2252  
  
2253  
  !include #1000509 // LFunctionPlusPrevious
2254  
  !include #1000510 // FNonMarkedAsList
2255  
  !include #1000511 // LWrap
2256  
  !include #1000512 // LPost
2257  
  !include #1000513 // FJoin
2258  
  !include #1000531 // FStringAsChars
2259  
  !include #1000532 // LUse
2260  
  
2261  
  static Object getFirst(Object list) {
2262  
    return ((List) list).isEmpty() ? null : ((List) list).get(0);
2263  
  }
2264  
}

Author comment

Began life as a copy of #720

download  show line numbers  debug dex  old transpilations   

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

Comments [hide]

ID Author/Program Comment Date
420 #1000610 (pitcher) 2015-08-18 18:54:10
419 #1000604 (pitcher) 2015-08-20 15:28:24

add comment

Snippet ID: #722
Snippet name: IOIOI Processor (v15)
Eternal ID of this version: #722/1
Text MD5: 80680ecf0a0294167b52a1ae19575130
Transpilation MD5: 7dac71cb41d0518f8cbdabc6fa44ec8b
Author: stefan
Category:
Type: JavaX source code
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2015-11-21 19:40:39
Source code size: 69945 bytes / 2264 lines
Pitched / IR pitched: No / Yes
Views / Downloads: 1042 / 1191
Referenced in: [show references]