AdventOfCode/AdventOfCode2023/Trebuchet/CalibrationPartOne.java
2024-12-02 18:26:58 -05:00

57 lines
1.6 KiB
Java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringReader;
public class CalibrationPartOne {
public static void main(String[] args) {
String coor = """
1abc2
pqr3stu8vwx
a1b2c3d4e5f
treb7uchet
""";
int total = 0;
try (
// let's first remove all the spaced lines and go through char by char
BufferedReader br = new BufferedReader(new FileReader("/home/ilyes/AdventOfCode/Trebuchet/Coordinates.txt"))) {
// BufferedReader br = new BufferedReader(new StringReader(coor))) {
String line;
while ((line = br.readLine()) != null) {
if (line.trim().isEmpty()) {
continue;
}
int first = -1;
int last = -1;
for (String c : line.split("")) {
// check for digits
if (Character.isDigit(c.charAt(0))) {
if (first == -1) {
// we add the first digit
first = Integer.parseInt(c);
}
// we add the last digit
last = Integer.parseInt(c);
}
}
// let's combine the first and the last digits then we do the addition (12 + 38
// + 15 + 77 = 142)
first = first * 10;
total += first + last;
// System.out.println(first + "" + last);
// the output would be
// 12
// 38
// 15
// 77 resulting in total of 142
}
System.out.println(total);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}