-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day4.java
86 lines (77 loc) · 2.13 KB
/
Day4.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
import java.util.Arrays;
import java.util.List;
public class Day4 {
static long day4(List<String> rooms) {
long idSum = 0;
int northPoleId = -1;
byte[] NORTH_POLE = "northpole".getBytes();
int[] count = new int[26]; // 0=a, 1=b, 2=c etc..
byte[] expctCS = new byte[5];
for (String room : rooms) {
int id = 0;
boolean isValid = true;
int csOffset = -1;
Arrays.fill(count, 0);
Arrays.fill(expctCS, (byte) -1);
byte[] bytes = room.getBytes();
for (int i = 0; i < bytes.length - 1; i++) {
byte c = bytes[i];
int k = c - 'a';
if (c == '[') {
csOffset = i + 1;
}
else if (csOffset != -1) {
// validate
isValid &= (expctCS[i - csOffset] == k);
}
else if (c >= 'a' && c <= 'z') {
int v = ++count[k];
for (int j = 0; j < expctCS.length; j++) {
byte k1 = expctCS[j];
if (k1 == -1 || v > count[k1] || (v == count[k1] && k <= k1) || k1 == c - 'a') {
// replace and swap
expctCS[j] = (byte) k;
k = k1;
if (k1 == -1 || k1 == c - 'a') {
// wasnt set or found the original location of k
break;
}
}
}
}
else if (c >= '0' && c <= '9') {
id = id * 10 + (c - '0');
}
}
if (isValid) {
idSum += id;
boolean isEqual = compareBytes(NORTH_POLE, bytes, id);
if (isEqual) {
northPoleId = id;
}
}
}
// Part 1
// return idSum;
// Part 2
return northPoleId;
}
/**
* shiftedBytes.startsWith(expected)
*/
private static boolean compareBytes(byte[] expected, byte[] bytes, int shift) {
for (int i = 0; i < expected.length; i++) {
byte b = bytes[i];
if (expected[i] != (b - 'a' + shift) % 26 + 'a') {
return false;
}
}
return true;
}
public static void main(String[] args) {
List<String> input = Util.readInput("day4.input");
// Part 1 : 137896
// Part 2 : 501
System.out.println(day4(input));
}
}