Skip to content

Commit

Permalink
refactor: fix some bugs and refactor day 1
Browse files Browse the repository at this point in the history
  • Loading branch information
Flashky committed Dec 1, 2024
1 parent 93bec5a commit 74aed7e
Showing 1 changed file with 13 additions and 24 deletions.
37 changes: 13 additions & 24 deletions src/main/java/com/adventofcode/flashk/day01/HistorianHysteria.java
Original file line number Diff line number Diff line change
Expand Up @@ -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<Long> left = new ArrayList<>();
private List<Long> right = new ArrayList<>();
private final List<Long> left = new ArrayList<>();
private final List<Long> right = new ArrayList<>();

public HistorianHysteria(List<String> 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]));
}
Expand All @@ -22,7 +25,7 @@ public Long solveA() {
List<Long> leftSorted = left.stream().sorted().toList();
List<Long> 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));
Expand All @@ -33,30 +36,16 @@ public Long solveA() {

public Long solveB() {

Long result = 0L;
Map<Long,Long> 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<Long,Long> occurrences = right.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

for(long number : left) {
result += number * occurrences.getOrDefault(number,0L);
}

return result;
}



}

0 comments on commit 74aed7e

Please sign in to comment.