Skip to content

Commit

Permalink
refactor: refactor day 1
Browse files Browse the repository at this point in the history
  • Loading branch information
Flashky committed Dec 1, 2024
1 parent de22659 commit 2b71d10
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 25 deletions.
36 changes: 12 additions & 24 deletions src/main/java/com/adventofcode/flashk/day01/HistorianHysteria.java
Original file line number Diff line number Diff line change
@@ -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<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 +24,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 +35,16 @@ public Long solveA() {

public Long solveB() {

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

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

return result;
}


}
2 changes: 1 addition & 1 deletion src/test/resources/inputs

0 comments on commit 2b71d10

Please sign in to comment.