71 lines
2.0 KiB
Java
71 lines
2.0 KiB
Java
package com.mattrixwv.adventOfCode24.days;
|
|
|
|
|
|
import java.util.ArrayList;
|
|
import java.util.List;
|
|
import java.util.Scanner;
|
|
import java.util.regex.Matcher;
|
|
import java.util.regex.Pattern;
|
|
|
|
import com.mattrixwv.Stopwatch;
|
|
|
|
|
|
public class Problem5 extends Problem{
|
|
private static final String inputFileName = "days/Problem5.txt";
|
|
|
|
|
|
public Problem5(){
|
|
super();
|
|
description = "Find the non-corrupted multiplication instructions that are allowed to run.";
|
|
result = "Unresolved";
|
|
}
|
|
|
|
public String runSolution(){
|
|
Stopwatch timer = new Stopwatch();
|
|
timer.start();
|
|
|
|
int sum = 0;
|
|
StringBuilder fileInput = new StringBuilder();
|
|
|
|
|
|
//Read the file
|
|
try(Scanner scanner = new Scanner(this.getClass().getClassLoader().getResourceAsStream(inputFileName))){
|
|
while(scanner.hasNext()){
|
|
fileInput.append(scanner.next());
|
|
}
|
|
}
|
|
|
|
//Pull out the valid references from the file
|
|
Pattern functionPattern = Pattern.compile("mul\\(\\d{1,3},\\d{1,3}\\)");
|
|
Matcher functionMatcher = functionPattern.matcher(fileInput.toString());
|
|
List<String> functions = new ArrayList<>();
|
|
while(functionMatcher.find()){
|
|
functions.add(functionMatcher.group());
|
|
}
|
|
StringBuilder functionString = new StringBuilder();
|
|
functions.forEach(func -> functionString.append(func));
|
|
|
|
//Perform the required multiplication
|
|
Pattern digitPattern = Pattern.compile("\\d{1,3}");
|
|
Matcher digitMatcher = digitPattern.matcher(functionString.toString());
|
|
while(digitMatcher.find()){
|
|
int num1 = Integer.parseInt(digitMatcher.group());
|
|
digitMatcher.find();
|
|
int num2 = Integer.parseInt(digitMatcher.group());
|
|
sum += (num1 * num2);
|
|
}
|
|
|
|
|
|
//Save the results
|
|
timer.stop();
|
|
result = "The sum of the non-corrupted multiplication instructions is " + sum + ".\nIt took " + timer.toString() + " to run the algorithm.";
|
|
return result;
|
|
}
|
|
}
|
|
|
|
/*
|
|
Find the non-corrupted multiplication instructions that are allowed to run
|
|
The sum of the non-corrupted multiplication instructions is 168539636.
|
|
It took 13.816 milliseconds to run the algorithm.
|
|
*/
|