-
Notifications
You must be signed in to change notification settings - Fork 2
/
Day009.java
111 lines (93 loc) · 3.21 KB
/
Day009.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
105
106
107
108
109
110
111
package com.catalinionescu.adventofcode.y2018;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import com.catalinionescu.adventofcode.common.Log;
public class Day009 {
public static String INPUT_URL = "https://adventofcode.com/2018/day/9/input";
public static String INPUT_FILE = "inputs/input009.txt";
class Node {
int value;
Node next;
Node prev;
public Node(Node prev, int value, Node next) {
this.value = value;
if (next == null) {
next = this;
}
this.next = next;
if (prev == null) {
prev = this;
}
this.prev = prev;
}
}
/**
* Adds a node 2 places to the right of the current node.
*
* @param current Current node
* @param value Value of the new node
* @return The new node
*/
private Node addAfter(Node current, int value) {
Node newNode = new Node(current.next, value, current.next.next);
current.next.next.prev = newNode;
current.next.next = newNode;
return newNode;
}
/**
* Removes the node 7 places to the left of the current node.
*
* @param current Current node
* @return Node that was removed
*/
private Node removeBefore(Node current) {
for (int i = 0; i < 7; i++) {
current = current.prev;
}
current.prev.next = current.next;
current.next.prev = current.prev;
return current;
}
private void main() throws IOException {
List<String> input = Files.readAllLines(Paths.get(INPUT_FILE));
if (input == null || input.isEmpty()) {
Log.logErrorMessage("Input data set is empty!");
return;
}
String parts[] = input.get(0).split(" ");
int playerCount = Integer.parseInt(parts[0]);
int configRounds = Integer.parseInt(parts[6]);
Log.logInfoMessage("Players: %d Rounds: %d", playerCount, configRounds);
int bothPartRounds[] = { configRounds, configRounds * 100 };
int part = 1;
for (int round : bothPartRounds) {
long elvesScores[] = new long[playerCount];
Node current = new Node(null, 0, null);
int currentPlayer;
for (int i = 1; i <= round; i++) {
if (i % 23 == 0) {
currentPlayer = i % playerCount;
elvesScores[currentPlayer] += i;
current = removeBefore(current);
elvesScores[currentPlayer] += current.value;
current = current.next;
} else {
current = addAfter(current, i);
}
}
long highestScore = 0;
for (int i = 0; i < elvesScores.length; i++) {
if (elvesScores[i] > highestScore) {
highestScore = elvesScores[i];
}
}
Log.logInfoMessage("High score for part %d is: %d", part, highestScore);
part++;
}
}
public static void main(String[] args) throws IOException {
new Day009().main();
}
}