-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day8.java
121 lines (97 loc) · 2.9 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package io.github.sirnikolai.days;
import io.github.sirnikolai.AbstractSolution;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class Day8 extends AbstractSolution {
@Override
public void Part1(String input) {
int acc = 0;
String[] arr = input.split("\n");
Node[] nodes = new Node[arr.length];
for(int i = 0; i < arr.length; i++) {
String[] sub = arr[i].split(" ");
nodes[i] = new Node(sub[0], Integer.parseInt(sub[1]));
}
for(int i = 0; i < nodes.length; ) {
Node next = nodes[i];
if(next.visited) {
System.out.println(acc);
return;
}
next.visited = true;
if(next.action.equals("nop")) {
i++;
} else if(next.action.equals("acc")) {
acc += next.val;
i++;
} else {
i += next.val;
}
}
}
@Override
public void Part2(String input) {
String[] arr = input.split("\n");
Node[] nodes = new Node[arr.length];
for(int i = 0; i < arr.length; i++) {
String[] sub = arr[i].split(" ");
nodes[i] = new Node(sub[0], Integer.parseInt(sub[1]));
}
for(Node n : nodes) {
if(n.action.equals("nop")) {
n.action = "jmp";
int[] ar = recurse(nodes);
if(ar[0] == 1) {
System.out.println(ar[1]);
return;
}
n.action = "nop";
for(Node n2 : nodes) {
n2.visited = false;
}
} else if(n.action.equals("jmp")) {
n.action = "nop";
int[] ar = recurse(nodes);
if(ar[0] == 1) {
System.out.println(ar[1]);
return;
}
n.action = "jmp";
for(Node n2 : nodes) {
n2.visited = false;
}
}
}
}
private int[] recurse(Node[] nodes) {
int acc = 0;
for(int i = 0; i < nodes.length; ) {
Node next = nodes[i];
if(next.visited) {
return new int[]{-1, -1};
}
next.visited = true;
if(next.action.equals("nop")) {
i++;
} else if(next.action.equals("acc")) {
acc += next.val;
i++;
} else {
i += next.val;
}
}
return new int[]{1, acc};
}
private static class Node {
boolean visited;
String action;
int val;
Node(String action, int val) {
this.action = action;
this.val = val;
this.visited = false;
}
}
}