-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay9.java
More file actions
108 lines (99 loc) · 2.43 KB
/
Day9.java
File metadata and controls
108 lines (99 loc) · 2.43 KB
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
import java.util.ArrayList;
import java.util.HashMap;
public class Day9 {
public static void main(String[] args) {
new Day9();
}
public Day9() {
ArrayList<String> input = ReadInput.read("res/input9.txt");
partOne(input);
partTwo(input);
}
private void partOne(ArrayList<String> input) {
HashMap<String, Boolean> tailVisited = new HashMap<String, Boolean>();
int res = 0;
Coord h = new Coord();
Coord t = new Coord();
for(String line : input) {
char instruction = line.split(" ")[0].charAt(0);
int dist = Integer.parseInt(line.split(" ")[1]);
for(int i = 0; i < dist; i++) {
moveHead(h, instruction);
moveTail(h, t, instruction);
if(tailVisited.get("" + t.x + "," + t.y) == null)
res++;
tailVisited.put("" + t.x + "," + t.y, true);
}
}
System.out.println(res);
}
private void partTwo(ArrayList<String> input) {
HashMap<String, Boolean> tailVisited = new HashMap<String, Boolean>();
int res = 0;
ArrayList<Coord> knots = new ArrayList<Coord>();
for(int i = 0; i < 10; i++)
knots.add(new Coord());
for(String line : input) {
char instruction = line.split(" ")[0].charAt(0);
int dist = Integer.parseInt(line.split(" ")[1]);
for(int counter = 0; counter < dist; counter++) {
moveHead(knots.get(0), instruction);
for(int i = 0; i < knots.size() - 1; i++) {
moveTail(knots.get(i), knots.get(i + 1), instruction);
if(i == knots.size() - 2) {
Coord t = knots.get(knots.size() - 1);
if(tailVisited.get("" + t.x + "," + t.y) == null)
res++;
tailVisited.put("" + t.x + "," + t.y, true);
}
}
}
}
System.out.println(res);
}
private void moveHead(Coord h, char instruction) {
if(instruction == 'U')
h.y++;
else if(instruction == 'D')
h.y--;
else if(instruction == 'R')
h.x++;
else
h.x--;
}
private void moveTail(Coord h, Coord t, char instruction) {
int xDiff = Math.abs(h.x - t.x);
int yDiff = Math.abs(h.y - t.y);
if(xDiff > 1 || yDiff > 1) {
if(xDiff == 0) {
t.y = h.y > t.y ? h.y - 1 : h.y + 1;
}
else if(yDiff == 0) {
t.x = h.x > t.x ? h.x - 1 : h.x + 1;
}
else if(h.x > t.x && h.y > t.y) {
t.x++;
t.y++;
}
else if(h.x > t.x && h.y < t.y) {
t.x++;
t.y--;
}
else if(h.x < t.x && h.y > t.y) {
t.x--;
t.y++;
}
else {
t.x--;
t.y--;
}
}
}
private class Coord {
public int x, y;
public Coord() {
this.x = 0;
this.y = 0;
}
}
}