blob: 5f4a7b513927676899d073c4f3d8bedc1b2c0a3f (
plain)
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
|
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.AbstractMap.SimpleEntry;
public class day15 {
public static void main(String args[]) throws IOException {
RandomAccessFile input = new RandomAccessFile("input", "r");
System.out.println("Day 15 Part 1: " + part1(input));
input.seek(0);
System.out.println("Day 15 Part 2: " + part2(input));
input.close();
}
public static String part1(RandomAccessFile input) throws IOException {
String[] init = input.readLine().split(",");
int sum = 0;
for(String s: init) {
sum += hash(s);
}
return Integer.toString(sum);
}
public static String part2(RandomAccessFile input) throws IOException {
String[] init = input.readLine().split(",");
PairList[] boxes = new PairList[256];
for (int i = 0; i < 256; i++) {
boxes[i] = new PairList();
}
for (String cmd: init) {
if (cmd.endsWith("-")) {
String[] cmda = cmd.split("-");
int box = hash(cmda[0]);
boxes[box].remove(cmda[0]);
} else {
String[] cmda = cmd.split("=");
int box = hash(cmda[0]);
boxes[box].put(cmda[0], Integer.parseInt(cmda[1]));
}
}
int sum = 0;
for (int i = 0; i < 256; i++) {
sum += ((i + 1) * boxes[i].power());
}
return Integer.toString(sum);
}
private static int hash(String s) {
int cur = 0;
for (int a: s.toCharArray()) {
cur += a;
cur *= 17;
cur %= 256;
}
return cur;
}
static class PairList {
ArrayList<SimpleEntry<String, Integer>> pairlist;
public PairList() {
pairlist = new ArrayList<>();
}
public void remove(String key) {
for (int i = 0; i < pairlist.size(); i++) {
if (pairlist.get(i).getKey().equals(key)) {
pairlist.remove(i);
return;
}
}
}
public void put(String key, Integer value) {
for (int i = 0; i < pairlist.size(); i++) {
if (pairlist.get(i).getKey().equals(key)) {
pairlist.get(i).setValue(value);
return;
}
}
pairlist.add(new SimpleEntry(key, value));
}
public int power() {
int sum = 0;
for (int i = 0; i < pairlist.size(); i++) {
sum += ((i + 1) * pairlist.get(i).getValue());
}
return sum;
}
}
}
|