From 2b71d10bdd121d5fe783ce8397eddde18f535285 Mon Sep 17 00:00:00 2001 From: Flashk Date: Sun, 1 Dec 2024 06:59:37 +0100 Subject: [PATCH] refactor: refactor day 1 --- .../flashk/day01/HistorianHysteria.java | 36 +++++++------------ src/test/resources/inputs | 2 +- 2 files changed, 13 insertions(+), 25 deletions(-) diff --git a/src/main/java/com/adventofcode/flashk/day01/HistorianHysteria.java b/src/main/java/com/adventofcode/flashk/day01/HistorianHysteria.java index cf10073..96688b7 100644 --- a/src/main/java/com/adventofcode/flashk/day01/HistorianHysteria.java +++ b/src/main/java/com/adventofcode/flashk/day01/HistorianHysteria.java @@ -1,18 +1,20 @@ package com.adventofcode.flashk.day01; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.function.Function; +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 +24,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 +35,16 @@ public Long solveA() { public Long solveB() { - Long result = 0L; - Map numberOccurrences = new HashMap<>(); - - for(Long number : left) { - Long occurrences = 0L; - if(numberOccurrences.containsKey(number)) { - occurrences = numberOccurrences.get(number); - result += number * numberOccurrences.get(number); - } else { + long result = 0L; - 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; } - } diff --git a/src/test/resources/inputs b/src/test/resources/inputs index 9ca3a30..4b6acbf 160000 --- a/src/test/resources/inputs +++ b/src/test/resources/inputs @@ -1 +1 @@ -Subproject commit 9ca3a3051eba4494f00900e400230f08a2eec01c +Subproject commit 4b6acbf2976dcb15bf592790fb857f0177ba056f