-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathDay4.java
86 lines (76 loc) · 2.19 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
package com.sbaars.adventofcode.year21.days;
import com.sbaars.adventofcode.common.grid.NumGrid;
import com.sbaars.adventofcode.year21.Day2021;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Day4 extends Day2021 {
public Day4() {
super(4);
}
public static void main(String[] args) {
new Day4().printParts();
}
@Override
public Object part1() {
var in = day();
String[] split = in.split("\n\n");
long[] nums = Arrays.stream(split[0].split(",")).mapToLong(Long::parseLong).toArray();
List<NumGrid> cards = IntStream.range(1, split.length).mapToObj(i -> split[i]).map(NumGrid::new).toList();
for (long num : nums) {
for (NumGrid card : cards) {
if (markCard(card, num) && checkCard(card)) {
return result(card, num);
}
}
}
return "";
}
private long result(NumGrid card, long num) {
return card.sumExcept(-1) * num;
}
private boolean markCard(NumGrid card, long num) {
return card.replace(num, -1);
}
private boolean checkCard(NumGrid grid) {
long[][] card = grid.grid;
for (long[] nums : card) {
if (Arrays.stream(nums).allMatch(n -> n == -1)) {
return true;
}
}
out:
for (int i = 0; i < card[0].length; i++) {
for (int j = 0; j < card[i].length; j++) {
if (card[j][i] != -1) {
continue out;
}
}
return true;
}
return false;
}
@Override
public Object part2() {
var in = day();
String[] split = in.split("\n\n");
long[] nums = Arrays.stream(split[0].split(",")).mapToLong(Long::parseLong).toArray();
List<NumGrid> cards = IntStream.range(1, split.length).mapToObj(i -> new NumGrid(split[i])).collect(Collectors.toCollection(ArrayList::new));
for (long num : nums) {
for (int i = 0; i < cards.size(); i++) {
NumGrid card = cards.get(i);
if (markCard(card, num) && checkCard(card)) {
if (cards.size() == 1) {
return result(card, num);
} else {
cards.remove(i);
i--;
}
}
}
}
return "";
}
}