-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day17.java
99 lines (75 loc) · 2.29 KB
/
Day17.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
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
public class Day17 {
private static MessageDigest digest;
private static final boolean[] OPEN = { false, false, false, false, false, false, false, false, false, false, false, true,
true, true, true, true };
static class Point {
int x;
int y;
String code;
Point(int x, int y, String code) {
this.x = x;
this.y = y;
this.code = code;
}
}
public static String part1(String input, final int endX, final int endY) {
Queue<Point> positions = new ArrayBlockingQueue<>(50);
positions.add(new Point(0, 0, input));
while (!positions.isEmpty()) {
Point p = positions.poll();
if (p.x == endX && p.y == endY) {
return p.code.substring(input.length());
}
addPoints(endX, endY, positions, p);
}
// no path
return null;
}
public static int part2(String input, final int endX, final int endY) {
Queue<Point> positions = new ArrayBlockingQueue<>(500);
positions.add(new Point(0, 0, input));
int max = -1;
while (!positions.isEmpty()) {
Point p = positions.poll();
if (p.x == endX && p.y == endY) {
max = Math.max(max, p.code.length());
}
else {
addPoints(endX, endY, positions, p);
}
}
return max - input.length();
}
private static void addPoints(int endX, int endY, Queue<Point> positions, Point p) {
byte[] hash = digest.digest(p.code.getBytes());
// up
if (p.x > 0 && OPEN[(hash[0] >> 4) & 0xf]) {
positions.add(new Point(p.x - 1, p.y, p.code + 'U'));
}
// down
if (p.x < endX && OPEN[hash[0] & 0x0f]) {
positions.add(new Point(p.x + 1, p.y, p.code + 'D'));
}
// left
if (p.y > 0 && OPEN[(hash[1] >> 4) & 0xf]) {
positions.add(new Point(p.x, p.y - 1, p.code + 'L'));
}
// right
if (p.y < endY && OPEN[hash[1] & 0x0f]) {
positions.add(new Point(p.x, p.y + 1, p.code + 'R'));
}
}
public static void main(String[] args) {
try {
digest = MessageDigest.getInstance("MD5");
System.out.println(part2("pslxynzg", 3, 3));
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
}