-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathd24.java
68 lines (63 loc) · 2.81 KB
/
d24.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
import java.util.stream.Collectors;
import static java.lang.System.*;
public class d24 {
public static void main(String[] args) {
var instructions = new ArrayList<Instruction>();
var reader = new BufferedReader(new InputStreamReader(in));
reader.lines().forEach(line -> { if (!line.isBlank()) instructions.add(Instruction.parse(line)); });
var programs = new ArrayList<List<Instruction>>();
for (var i : instructions) {
if ("inp".equals(i.op()))
programs.add(new ArrayList<>());
else
programs.get(programs.size() - 1).add(i);
}
var seen = new ArrayList<Set<Integer>>();
for (int i = 0; i < programs.size(); i++) seen.add(new HashSet<>());
run(programs, new int[] {9, 8, 7, 6, 5, 4, 3, 2, 1}, new Stack<Integer>(), seen, 0);
for (int i = 0; i < programs.size(); i++) seen.get(i).clear();
run(programs, new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9}, new Stack<Integer>(), seen, 0);
}
static int run(List<Instruction> program, int w, int z) {
var regs = new HashMap<String, Integer>();
regs.put("w", w);
regs.put("z", z);
regs.put("x", 0);
regs.put("y", 0);
for (var i : program) {
var b = regs.containsKey(i.arg2()) ? regs.get(i.arg2()) : Integer.parseInt(i.arg2());
switch (i.op()) {
case "add": regs.put(i.arg1(), regs.get(i.arg1()) + b); break;
case "mul": regs.put(i.arg1(), regs.get(i.arg1()) * b); break;
case "div": regs.put(i.arg1(), regs.get(i.arg1()) / b); break;
case "mod": regs.put(i.arg1(), regs.get(i.arg1()) % b); break;
case "eql": regs.put(i.arg1(), regs.get(i.arg1()).equals(b) ? 1 : 0); break;
}
}
return regs.get("z");
}
static void run(List<List<Instruction>> programs, int[] inputs, Stack<Integer> stack, List<Set<Integer>> seen, int z) {
var i = stack.size();
if (i >= programs.size() || seen.get(i).contains(z)) return;
seen.get(i).add(z);
for (var w : inputs) {
var zz = run(programs.get(i), w, z);
stack.push(w);
if (zz == 0 && stack.size() >= programs.size()) {
out.println(stack.stream().map(Object::toString).collect(Collectors.joining()));
return;
}
run(programs, inputs, stack, seen, zz);
stack.pop();
}
}
record Instruction (String op, String arg1, String arg2) {
static Instruction parse(String line) {
var triple = line.split("\\s");
return new Instruction(triple[0], triple[1], triple.length > 2 ? triple[2] : "");
}
}
}