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