-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathDay4.java
57 lines (45 loc) · 1.73 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
package com.sbaars.adventofcode.year20.days;
import com.sbaars.adventofcode.year20.Day2020;
import java.util.Arrays;
import java.util.Map;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import static java.util.stream.Collectors.toSet;
public class Day4 extends Day2020 {
private static final Map<String, String> expected = Map.of("byr", "^(200[0-2]|19[2-9][0-9])$",
"iyr", "^(2020|201[0-9])$",
"eyr", "^(2030|202[0-9])$",
"hgt", "^((1([5-8][0-9]|9[0-3])cm)|((59|6[0-9]|7[0-6])in))$",
"hcl", "^(#[0-9a-f]{6})$",
"ecl", "^(amb|blu|brn|gry|grn|hzl|oth)$",
"pid", "^[0-9]{9}$");
public Day4() {
super(4);
}
public static void main(String[] args) {
new Day4().printParts();
}
@Override
public Object part1() {
return verifyPassports(this::valid1);
}
@Override
public Object part2() {
return verifyPassports(this::valid2);
}
public long verifyPassports(Predicate<String[]> verifyFunction) {
String[][] passports = Arrays.stream(day().split("\n\n")).map(str -> str.replace("\n", " ")).map(str -> str.split(" ")).toArray(String[][]::new);
return Arrays.stream(passports).filter(verifyFunction).count();
}
public boolean valid1(String[] passport) {
return Arrays.stream(passport).map(s -> s.substring(0, 3)).collect(toSet()).containsAll(expected.keySet());
}
public boolean valid2(String[] passport) {
return valid1(passport) && Arrays.stream(passport).map(s -> s.split(":")).allMatch(s -> matchesRegex(s[0], s[1]));
}
public boolean matchesRegex(String key, String validate) {
if (!expected.containsKey(key)) return true;
final Pattern pattern = Pattern.compile(expected.get(key));
return pattern.matcher(validate).matches();
}
}