-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathDay14.java
104 lines (90 loc) · 3.16 KB
/
Day14.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
package com.sbaars.adventofcode.year16.days;
import com.sbaars.adventofcode.year16.Day2016;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Day14 extends Day2016 {
private static final int REQUIRED_KEYS = 64;
private static final int WINDOW_SIZE = 1000;
private static final int STRETCH_COUNT = 2016;
public Day14() {
super(14);
}
public static void main(String[] args) {
new Day14().printParts();
}
private String getMD5Hash(String input) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] digest = md.digest(input.getBytes());
StringBuilder hexString = new StringBuilder();
for (byte b : digest) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
private String getStretchedHash(String input) {
String hash = getMD5Hash(input);
for (int i = 0; i < STRETCH_COUNT; i++) {
hash = getMD5Hash(hash);
}
return hash;
}
private Character findTriple(String hash) {
for (int i = 0; i < hash.length() - 2; i++) {
if (hash.charAt(i) == hash.charAt(i + 1) &&
hash.charAt(i) == hash.charAt(i + 2)) {
return hash.charAt(i);
}
}
return null;
}
private boolean hasFiveInARow(String hash, char c) {
String target = String.valueOf(c).repeat(5);
return hash.contains(target);
}
private int findIndexOf64thKey(boolean useStretching) {
String salt = day().trim();
Map<Integer, String> hashes = new HashMap<>();
List<Integer> keys = new ArrayList<>();
int index = 0;
while (keys.size() < REQUIRED_KEYS) {
String hash = hashes.computeIfAbsent(index, i -> {
String input = salt + i;
return useStretching ? getStretchedHash(input) : getMD5Hash(input);
});
Character triple = findTriple(hash);
if (triple != null) {
// Look ahead for quintuple
for (int j = index + 1; j <= index + WINDOW_SIZE; j++) {
String nextHash = hashes.computeIfAbsent(j, i -> {
String input = salt + i;
return useStretching ? getStretchedHash(input) : getMD5Hash(input);
});
if (hasFiveInARow(nextHash, triple)) {
keys.add(index);
break;
}
}
}
index++;
}
return keys.get(REQUIRED_KEYS - 1);
}
@Override
public Object part1() {
return findIndexOf64thKey(false);
}
@Override
public Object part2() {
return findIndexOf64thKey(true);
}
}