|
| 1 | +package com.icecreamhead.adventofcode.q5; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Arrays; |
| 5 | +import java.util.HashMap; |
| 6 | +import java.util.HashSet; |
| 7 | +import java.util.List; |
| 8 | +import java.util.Map; |
| 9 | +import java.util.Map.Entry; |
| 10 | +import java.util.Set; |
| 11 | + |
| 12 | +public class PrintQueue { |
| 13 | + |
| 14 | + long pt1(List<String> input) { |
| 15 | + |
| 16 | + Map<Integer, Set<Integer>> rules = buildRules(input); |
| 17 | + |
| 18 | + input.removeFirst(); // skip line break |
| 19 | + |
| 20 | + return input.stream() |
| 21 | + .map(in -> Arrays.stream(in.split(",")).mapToInt(Integer::parseInt).toArray()) |
| 22 | + .filter(up -> accept(up, rules)) |
| 23 | + .mapToInt(up -> up[up.length / 2]) |
| 24 | + .sum(); |
| 25 | + } |
| 26 | + |
| 27 | + long pt2(List<String> input) { |
| 28 | + |
| 29 | + Map<Integer, Set<Integer>> rules = buildRules(input); |
| 30 | + |
| 31 | + input.removeFirst(); // skip line break |
| 32 | + |
| 33 | + return input.stream() |
| 34 | + .map(in -> Arrays.stream(in.split(",")).mapToInt(Integer::parseInt).toArray()) |
| 35 | + .filter(up -> !accept(up, rules)) |
| 36 | + .map(up -> fixIt(up, rules)) |
| 37 | + .mapToInt(up -> up[up.length / 2]) |
| 38 | + .sum(); |
| 39 | + } |
| 40 | + |
| 41 | + private static int[] fixIt(int[] update, Map<Integer, Set<Integer>> rules) { |
| 42 | + ArrayList<Integer> incorrect = new ArrayList<>(Arrays.stream(update).boxed().toList()); |
| 43 | + |
| 44 | + rules.forEach((r, vs) -> { |
| 45 | + if (incorrect.contains(r)) { |
| 46 | + vs.forEach(v -> { |
| 47 | + if (incorrect.contains(v) && incorrect.indexOf(r) > incorrect.indexOf(v)) { |
| 48 | + // move r before v |
| 49 | + incorrect.remove(r); |
| 50 | + incorrect.add(incorrect.indexOf(v), r); |
| 51 | + } |
| 52 | + }); |
| 53 | + } |
| 54 | + }); |
| 55 | + return incorrect.stream().mapToInt(i -> i).toArray(); |
| 56 | + } |
| 57 | + |
| 58 | + private static boolean accept(int[] update, Map<Integer, Set<Integer>> rules) { |
| 59 | + for (int i = 0; i < update.length; i++) { |
| 60 | + if (rules.containsKey(update[i])) { |
| 61 | + Set<Integer> ruleSet = rules.get(update[i]); |
| 62 | + for (int j = i - 1; j >= 0; j--) { |
| 63 | + if (ruleSet.contains(update[j])) { |
| 64 | + return false; |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + } |
| 69 | + return true; |
| 70 | + } |
| 71 | + |
| 72 | + private static Map<Integer, Set<Integer>> buildRules(List<String> input) { |
| 73 | + Map<Integer, Set<Integer>> rules = new HashMap<>(); |
| 74 | + while (input.getFirst().contains("|")) { |
| 75 | + String[] parts = input.removeFirst().split("\\|"); |
| 76 | + rules.computeIfAbsent(Integer.parseInt(parts[0]), k -> new HashSet<>()).add(Integer.parseInt(parts[1])); |
| 77 | + } |
| 78 | + return rules; |
| 79 | + } |
| 80 | + |
| 81 | +} |
0 commit comments