-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day8.java
91 lines (80 loc) · 1.98 KB
/
Day8.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Day8 {
public static void main(String[] args) throws IOException {
List<String> lines = Files.readAllLines(Paths.get("input8.txt"));
Set<Integer> linesExecuted = new HashSet<>();
int accumulator = 0, i = 0;
while(true) {
if(linesExecuted.contains(i)) {
System.out.println(accumulator);
break;
}
linesExecuted.add(i);
String instr = lines.get(i).split(" ")[0];
int value = Integer.parseInt(lines.get(i).split(" ")[1]);
switch (instr) {
case "nop":
++i;
break;
case "jmp":
i = i + value;
break;
case "acc":
accumulator += value;
++i;
break;
default:
break;
}
}
System.out.println(findInstruction(lines));
}
public static int findInstruction(List<String> lines) {
Set<Integer> linesExecuted = new HashSet<>();
Set<Integer> linesChanged = new HashSet<>();
int accumulator = 0, i = 0;
boolean changedInInteration = false;
while(true) {
if(linesExecuted.contains(i)) {
changedInInteration = false;
linesExecuted.clear();
accumulator = 0;
i = 0;
continue;
}
linesExecuted.add(i);
String instr = lines.get(i).split(" ")[0];
int value = Integer.parseInt(lines.get(i).split(" ")[1]);
if(instr.equals("jmp") && changedInInteration == false && !linesChanged.contains(i)) {
changedInInteration = true;
linesChanged.add(i);
instr = "nop";
} else if(instr.equals("nop") && changedInInteration == false && !linesChanged.contains(i)) {
changedInInteration = true;
linesChanged.add(i);
instr = "jmp";
}
switch (instr) {
case "nop":
++i;
break;
case "jmp":
i = i + value;
break;
case "acc":
accumulator += value;
++i;
break;
default:
break;
}
if(i >= lines.size()) break;
}
return accumulator;
}
}