|
| 1 | +package org.anne.aoc2015; |
| 2 | + |
| 3 | +import org.anne.common.Day; |
| 4 | + |
| 5 | +import java.util.*; |
| 6 | +import java.util.regex.Matcher; |
| 7 | +import java.util.regex.Pattern; |
| 8 | + |
| 9 | +public class Day16 extends Day { |
| 10 | + public static void main(String[] args) { |
| 11 | + new Day16().run(); |
| 12 | + } |
| 13 | + |
| 14 | + @Override |
| 15 | + public void execute() { |
| 16 | + setName("Aunt Sue"); |
| 17 | + List<String> input = readFile(); |
| 18 | + setPart1(part1(input)); |
| 19 | + setPart2(part2(input)); |
| 20 | + } |
| 21 | + |
| 22 | + private static final Pattern PATTERN = Pattern.compile("Sue (\\d+): (\\w+: \\d+), (\\w+: \\d+), (\\w+: \\d+)"); |
| 23 | + private static final List<String> MFCSAM = List.of("children: 3", "cats: 7", "samoyeds: 2", "pomeranians: 3", |
| 24 | + "akitas: 0", "vizslas: 0", "goldfish: 5", "trees: 3", "cars: 2", "perfumes: 1"); |
| 25 | + |
| 26 | + public static String part1(List<String> input) { |
| 27 | + return input.stream() |
| 28 | + .map(PATTERN::matcher) |
| 29 | + .filter(Matcher::find) |
| 30 | + .filter(m -> MFCSAM.contains(m.group(2)) && MFCSAM.contains(m.group(3)) && MFCSAM.contains(m.group(4))) |
| 31 | + .map(m -> m.group(1)) |
| 32 | + .findFirst() |
| 33 | + .orElseThrow(); |
| 34 | + } |
| 35 | + |
| 36 | + public static String part2(List<String> input) { |
| 37 | + Map<String, Integer> mfcsam = MFCSAM.stream() |
| 38 | + .map(s -> s.split(": ")) |
| 39 | + .collect(HashMap::new, (m, p) -> m.put(p[0], Integer.parseInt(p[1])), Map::putAll); |
| 40 | + |
| 41 | + return input.stream() |
| 42 | + .map(PATTERN::matcher) |
| 43 | + .filter(Matcher::find) |
| 44 | + .filter(m -> matchesExpected(m.group(2), mfcsam) && matchesExpected(m.group(3), mfcsam) && matchesExpected(m.group(4), mfcsam)) |
| 45 | + .map(m -> m.group(1)) |
| 46 | + .findFirst() |
| 47 | + .orElseThrow(); |
| 48 | + } |
| 49 | + |
| 50 | + private static boolean matchesExpected(String s, Map<String, Integer> map) { |
| 51 | + var parts = s.split(": "); |
| 52 | + int actual = Integer.parseInt(parts[1]); |
| 53 | + int expected = map.get(parts[0]); |
| 54 | + |
| 55 | + return switch (parts[0]) { |
| 56 | + case "cats", "trees" -> actual > expected; |
| 57 | + case "pomeranians", "goldfish" -> actual < expected; |
| 58 | + default -> actual == expected; |
| 59 | + }; |
| 60 | + } |
| 61 | +} |
0 commit comments