-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay09.java
65 lines (59 loc) · 1.64 KB
/
Day09.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
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @author Zachary Cockshutt
* @since 2023-12-09
*/
public class Day09 extends Day
{
@Override
public String partOne() throws IOException
{
return sumFutureReadings(false);
}
@Override
public String partTwo() throws IOException
{
return sumFutureReadings(true);
}
private String sumFutureReadings(boolean isPartTwo) throws IOException
{
var sum = new AtomicLong(0L);
this.input(s ->
{
var sqnc = parseSequence(s, isPartTwo);
sum.set(sum.get() + extrapolate(sqnc));
});
return sum.toString();
}
private long[] parseSequence(String s, boolean isPartTwo)
{
var sqnc = Stream.of(s.split(" "))
.map(Long::parseLong)
.collect(Collectors.toCollection(ArrayList::new));
if (isPartTwo) { Collections.reverse(sqnc); }
return sqnc.stream().mapToLong(x->x).toArray();
}
private long extrapolate(long[] sqnc)
{
long future = 0;
while (!isZeroed(sqnc))
{
future += sqnc[sqnc.length-1];
var next = new long[sqnc.length-1];
for (int i=0; i<next.length; i++) { next[i] = sqnc[i+1]-sqnc[i]; }
sqnc = next;
}
return future;
}
private boolean isZeroed(long[] sqnc)
{
for (int i = 0; i < sqnc.length; i++)
if (sqnc[i] != 0) { return false; }
return true;
}
}