Complete day 1

This commit is contained in:
2024-12-09 20:23:56 -05:00
parent 955310d32b
commit 664a02115d
6 changed files with 1157 additions and 3 deletions

View File

@@ -0,0 +1,84 @@
package com.mattrixwv.adventOfCode24.days;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import com.mattrixwv.Stopwatch;
public class Problem2 extends Problem{
private static final String inputFileName = "days/Problem1.txt";
public Problem2(){
super();
description = "Find the similarity score between the two columsn of numbers";
result = "Unresolved";
}
@Override
public String runSolution(){
Stopwatch timer = new Stopwatch();
timer.start();
int totalSimilarityScore = 0;
ArrayList<Integer> column1 = new ArrayList<>(1000);
ArrayList<Integer> column2 = new ArrayList<>(1000);
//Read elements from the file into memory
try(Scanner scanner = new Scanner(this.getClass().getClassLoader().getResourceAsStream(inputFileName))){
scanner.useDelimiter("\\s+");
while(scanner.hasNext()){
String token1 = scanner.next();
String token2 = scanner.next();
column1.add(Integer.parseInt(token1));
column2.add(Integer.parseInt(token2));
}
}
//Sort the two lists of ids
Collections.sort(column1);
Collections.sort(column2);
//Get the similarity score of each elements and keep a running sum
//The similarity score is the element in column 1 multiplied by the number of times it appears in column 2
for(Integer num : column1){
int count = count(num, column2);
totalSimilarityScore += (num * count);
}
//Save the results
timer.stop();
result = "The similarity score between the two columns of numbers is " + totalSimilarityScore + ".\nIt took " + timer.toString() + " to run the algorithm.";
return result;
}
//Get the number of times a number appears in the list
private int count(int num, List<Integer> list){
int cnt = 0;
for(Integer n : list){
if(n == num){
++cnt;
}
if(n > num){
break;
}
}
return cnt;
}
}
/*
Find the similarity score between the two columns of numbers
The similarity score between the two columns of numbers is 24316233.
It took 17.875 milliseconds to run the algorithm.
*/