-
Notifications
You must be signed in to change notification settings - Fork 17
/
Day14.java
94 lines (78 loc) · 2.24 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
package com.sbaars.adventofcode.year18.days;
import com.sbaars.adventofcode.year18.Day2018;
import java.util.ArrayList;
import java.util.List;
public class Day14 extends Day2018 {
public Day14() {
super(14);
}
public static void main(String[] args) {
new Day14().printParts();
}
@Override
public Object part1() {
return getScores(dayNumber());
}
@Override
public Object part2() {
return findScoreSequence(dayNumber());
}
public String getScores(long numRecipes) {
List<Integer> scores = startScores();
int elf1 = 0;
int elf2 = 1;
while (scores.size() < numRecipes + 10) {
int newScore = scores.get(elf1) + scores.get(elf2);
if (newScore >= 10) {
scores.add(newScore / 10);
}
scores.add(newScore % 10);
elf1 = (elf1 + scores.get(elf1) + 1) % scores.size();
elf2 = (elf2 + scores.get(elf2) + 1) % scores.size();
}
StringBuilder sb = new StringBuilder();
for (long i = numRecipes; i < numRecipes + 10; i++) {
sb.append(scores.get(Math.toIntExact(i)));
}
return sb.toString();
}
public int findScoreSequence(long numRecipes) {
List<Integer> scores = startScores();
int elf1 = 0;
int elf2 = 1;
String sequence = String.valueOf(numRecipes);
int[] seq = sequence.chars().map(c -> c - '0').toArray();
int seqIndex = 0;
while (true) {
int newScore = scores.get(elf1) + scores.get(elf2);
if (newScore >= 10) {
scores.add(newScore / 10);
if (scores.get(scores.size() - 1) == seq[seqIndex]) {
seqIndex++;
if (seqIndex == seq.length) {
return scores.size() - seq.length;
}
} else {
seqIndex = 0;
}
}
scores.add(newScore % 10);
if (scores.get(scores.size() - 1) == seq[seqIndex]) {
seqIndex++;
if (seqIndex == seq.length) {
return scores.size() - seq.length;
}
} else {
seqIndex = 0;
}
elf1 = (elf1 + scores.get(elf1) + 1) % scores.size();
elf2 = (elf2 + scores.get(elf2) + 1) % scores.size();
}
}
private List<Integer> startScores() {
List<Integer> scores = new ArrayList<>();
scores.add(3);
scores.add(7);
return scores;
}
}