AdventOfCode/Trebuchet/TrebuchetPartTwo.java

96 lines
2.7 KiB
Java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;
public class TrebuchetPartTwo {
public static void main(String[] args) {
// Mapping of words to string digits
HashMap<String, String> 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");
// Sample string input
String str = """
two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen
""";
try {
String line;
int total = 0;
// Read the string line by line
BufferedReader br = new BufferedReader(new FileReader("/home/ilyes/AdventOfCode/Trebuchet/snowyCoordinates.txt"));
// // stringreader(str)
while ((line = br.readLine()) != null) {
// Skip empty lines
if (line.trim().isEmpty()) {
continue;
}
String firstDigit = null;
String lastDigit = null;
// Find the first digit
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
if (Character.isDigit(c)) {
firstDigit = String.valueOf(c);
break;
}
for (Map.Entry<String, String> entry : stringToDigit.entrySet()) {
if (line.startsWith(entry.getKey(), i)) {
firstDigit = entry.getValue();
break;
}
}
if (firstDigit != null)
break;
}
// Find the last digit
for (int i = line.length() - 1; i >= 0; i--) {
char c = line.charAt(i);
if (Character.isDigit(c)) {
lastDigit = String.valueOf(c);
break;
}
for (Map.Entry<String, String> entry : stringToDigit.entrySet()) {
if (line.startsWith(entry.getKey(), i)) {
lastDigit = entry.getValue();
break;
}
}
if (lastDigit != null)
break;
}
// Combine first and last digits if found
if (firstDigit != null && lastDigit != null) {
int sum = (Integer.parseInt(firstDigit) * 10) + Integer.parseInt(lastDigit);
total += sum;
}
}
// Output the total sum
System.out.println("Total for Part Two = " + total);
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}