Created
December 1, 2023 22:09
-
-
Save dhoss/21186139bcd46db92a93e3c57be12430 to your computer and use it in GitHub Desktop.
AoC Day 1 Part 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package in.stonecolddev; | |
import java.util.List; | |
import java.util.Map; | |
public class DayOne implements DayRunner { | |
public static String partOne(List<String> data) { | |
Integer sum = 0; | |
for (String line : data) { | |
Integer firstNumber = null; | |
Integer lastNumber = null; | |
Integer numbersSeen = 0; | |
for (char c : line.toCharArray()) { | |
if (Character.isDigit(c)) { | |
numbersSeen++; | |
Integer numericValue = Character.getNumericValue(c); | |
if (firstNumber == null) { | |
firstNumber = numericValue; | |
} else { | |
lastNumber = numericValue; | |
} | |
} | |
} | |
if (numbersSeen < 2) { | |
lastNumber = firstNumber; | |
} | |
sum += Integer.parseInt("%d%d".formatted(firstNumber, lastNumber)); | |
} | |
return sum.toString(); | |
} | |
public static String partTwo(List<String> data) { | |
Integer sum = 0; | |
for (String line : data) { | |
Integer firstNumber = null; | |
Integer lastNumber = null; | |
Integer numbersSeen = 0; | |
Map<String, Integer> numbers = Map.of( | |
"one", 1, | |
"two", 2, | |
"three", 3, | |
"four", 4, | |
"five", 5, | |
"six", 6, | |
"seven", 7, | |
"eight", 8, | |
"nine", 9); | |
for (String number : numbers.keySet().stream().sorted().toList()) { | |
System.out.printf("Checking %s for number %d%n", line, numbers.get(number)); | |
if (line.toLowerCase().contains(number)) { | |
numbersSeen++; | |
Integer actualNumber = numbers.get(number); | |
if (firstNumber == null) { | |
firstNumber = actualNumber; | |
System.out.printf("%d is the first number%n", firstNumber); | |
} else { | |
lastNumber = actualNumber; | |
System.out.printf("%d is the last number%n", lastNumber); | |
} | |
} | |
} | |
for (char c : line.toCharArray()) { | |
if (Character.isDigit(c)) { | |
numbersSeen++; | |
if (firstNumber == null) { | |
firstNumber = Character.getNumericValue(c); | |
} else { | |
lastNumber = Character.getNumericValue(c); | |
} | |
} | |
} | |
if (numbersSeen < 2) { | |
lastNumber = firstNumber; | |
} | |
sum += Integer.parseInt("%d%d".formatted(firstNumber, lastNumber)); | |
} | |
return sum.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment