99 lines
2.7 KiB
Java
99 lines
2.7 KiB
Java
import java.io.BufferedReader;
|
|
import java.io.StringReader;
|
|
import java.util.HashMap;
|
|
|
|
/**
|
|
* CalibrationPartTwo
|
|
*/
|
|
public class CalibrationPartTwo {
|
|
|
|
public static void main(String[] args) {
|
|
|
|
// HashMap to map word representations of digits to their corresponding numeric
|
|
// values
|
|
HashMap<String, Integer> stringToDigit = new HashMap<>();
|
|
stringToDigit.put("one", 1);
|
|
stringToDigit.put("two", 2);
|
|
stringToDigit.put("three", 3);
|
|
stringToDigit.put("four", 4);
|
|
stringToDigit.put("five", 5);
|
|
stringToDigit.put("six", 6);
|
|
stringToDigit.put("seven", 7);
|
|
stringToDigit.put("eight", 8);
|
|
stringToDigit.put("nine", 9);
|
|
|
|
// String input
|
|
String str = """
|
|
two1nine
|
|
eightwothree
|
|
abcone2threexyz
|
|
xtwone3four
|
|
4nineeightseven2
|
|
zoneight234
|
|
7pqrstsixteen
|
|
""";
|
|
|
|
try {
|
|
BufferedReader br = new BufferedReader(new StringReader(str));
|
|
String line;
|
|
int total = 0;
|
|
|
|
while ((line = br.readLine()) != null) {
|
|
if (line.trim().isEmpty()) {
|
|
continue; // Skip empty lines
|
|
}
|
|
|
|
StringBuilder wordBuffer = new StringBuilder();
|
|
int firstDigit = -1;
|
|
int lastDigit = -1;
|
|
|
|
for (int i = 0; i < line.length(); i++) {
|
|
char c = line.charAt(i);
|
|
|
|
// Build a word if we encounter alphabetic characters
|
|
if (Character.isLetter(c)) {
|
|
wordBuffer.append(c);
|
|
String currentWord = wordBuffer.toString();
|
|
|
|
// Check if the current word matches a digit word
|
|
if (stringToDigit.containsKey(currentWord)) {
|
|
int num = stringToDigit.get(currentWord);
|
|
if (firstDigit == -1) {
|
|
firstDigit = num;
|
|
}
|
|
lastDigit = num;
|
|
wordBuffer.setLength(0); // Clear the buffer after processing the word
|
|
}
|
|
}
|
|
|
|
// If we encounter a digit, process it directly
|
|
else if (Character.isDigit(c)) {
|
|
int num = Character.getNumericValue(c);
|
|
if (firstDigit == -1) {
|
|
firstDigit = num;
|
|
}
|
|
lastDigit = num;
|
|
}
|
|
|
|
// If we encounter a non-alphabetic, non-digit character, reset the word buffer
|
|
else {
|
|
wordBuffer.setLength(0);
|
|
}
|
|
}
|
|
|
|
// Combine the first and last digits
|
|
if (firstDigit != -1 && lastDigit != -1) {
|
|
int sum = (firstDigit * 10) + lastDigit;
|
|
System.out.println(sum);
|
|
total += sum;
|
|
}
|
|
}
|
|
|
|
// Output the final total
|
|
System.out.println("Total for Part Two = " + total);
|
|
} catch (Exception e) {
|
|
e.printStackTrace();
|
|
}
|
|
}
|
|
}
|