diff --git a/src/main/java/com/adventofcode/flashk/day01/HistorianHysteria.java b/src/main/java/com/adventofcode/flashk/day01/HistorianHysteria.java index cf10073..05b122f 100644 --- a/src/main/java/com/adventofcode/flashk/day01/HistorianHysteria.java +++ b/src/main/java/com/adventofcode/flashk/day01/HistorianHysteria.java @@ -4,15 +4,18 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collector; +import java.util.stream.Collectors; public class HistorianHysteria { - private List left = new ArrayList<>(); - private List right = new ArrayList<>(); + private final List left = new ArrayList<>(); + private final List right = new ArrayList<>(); public HistorianHysteria(List input) { for(String line : input) { - String[] split = line.split(" "); + String[] split = line.split(" {3}"); left.add(Long.valueOf(split[0])); right.add(Long.valueOf(split[1])); } @@ -22,7 +25,7 @@ public Long solveA() { List leftSorted = left.stream().sorted().toList(); List rightSorted = right.stream().sorted().toList(); - Long result = 0L; + long result = 0L; for(int i = 0; i < leftSorted.size(); i++) { result += Math.abs(leftSorted.get(i)-rightSorted.get(i)); @@ -33,30 +36,16 @@ public Long solveA() { public Long solveB() { - Long result = 0L; - Map numberOccurrences = new HashMap<>(); + long result = 0L; - for(Long number : left) { - Long occurrences = 0L; - if(numberOccurrences.containsKey(number)) { - occurrences = numberOccurrences.get(number); - result += number * numberOccurrences.get(number); - } else { - - for(Long numberRight : right) { - if(number.equals(numberRight)) { - occurrences++; - } - } - - numberOccurrences.put(number, occurrences); - } - result += number * occurrences; + Map occurrences = right.stream() + .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); + for(long number : left) { + result += number * occurrences.getOrDefault(number,0L); } return result; } - - + }