Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Advent2018;
- import util.AdventOfCode;
- import java.util.Collections;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- public class Day4 extends AdventOfCode {
- Map<Integer, Map<Integer, Integer>> guards;
- public Day4(List<String> input) {
- super(input);
- title = "Repose Record";
- part1Description = "Most sleepy guard * most asleep minute: ";
- part2Description = "Any guard * Most Sleepy Minute: ";
- }
- @Override
- public Object part1() {
- int max = 0;
- int maxId = 0;
- int maxMinute = 0;
- for (Map.Entry<Integer, Map<Integer, Integer>> guard : guards.entrySet()) {
- int val = guard.getValue().getOrDefault(9999, 0);
- guard.getValue().remove(9999);
- if (val > max) {
- max = val;
- maxId = guard.getKey();
- maxMinute = guard.getValue().entrySet().stream()
- .max(Map.Entry.comparingByValue())
- .get().getKey();
- }
- }
- return maxId * maxMinute;
- }
- @Override
- public Object part2() {
- int max = 0;
- int maxMinute = 0;
- int maxId = 0;
- for (Map.Entry<Integer, Map<Integer, Integer>> guard : guards.entrySet()) {
- if (guard.getValue().size() == 0) continue;
- int min = guard.getValue().entrySet().stream()
- .max(Map.Entry.comparingByValue())
- .get().getKey();
- if (guard.getValue().get(min) > max) {
- max = guard.getValue().getOrDefault(min, 0);
- maxMinute = min;
- maxId = guard.getKey();
- }
- }
- return maxMinute * maxId;
- }
- @Override
- public void parse() {
- guards = new HashMap<>();
- Collections.sort(input);
- Pattern p = Pattern.compile("\\[1518-([0-9]+)-([0-9]+) ([0-9]{2}):([0-9]{2})] ([\\w\\W]+)$");
- Pattern p2 = Pattern.compile("Guard #(\\d+)");
- int currentGuard = 0;
- int startTime = 0;
- for (String line : input) {
- Matcher m = p.matcher(line);
- if (m.find()) {
- int min = Integer.parseInt(m.group(4));
- String detail = m.group(5);
- if (detail.startsWith("Guard")) {
- Matcher m2 = p2.matcher(detail);
- if (m2.find()) {
- currentGuard = Integer.parseInt(m2.group(1));
- guards.putIfAbsent(currentGuard, new HashMap<>());
- }
- } else {
- if (detail.equals("falls asleep")) {
- startTime = min;
- } else {
- for (int i = startTime; i < min; i++) {
- // frequency map
- guards.get(currentGuard).put(i, guards.get(currentGuard).getOrDefault(i, 0) + 1);
- // update total sum in freq map
- guards.get(currentGuard).put(9999, guards.get(currentGuard).getOrDefault(9999, 0) + 1);
- }
- }
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement