Something is wrong with global snow production, and you’ve been selected to take a look. The Elves have even given you a map; on it, they’ve used stars to mark the top fifty locations that are likely to be having problems.
Solution in Java
Full source can be found: in GitHub
Part 1
In the first part of this years Advent of Code we are requested to find the first and last digit in a string. The input will consists out of multiple of these strings.
This can be done relatively easy by looping over all lines and then filtering out the digits for each line. All that is left is adding the first and last digit together to create a new number and then summing all these numbers.
1public void part1() {
2 var answer = inputLoader.splitOnNewLine()
3 .map(this::getBoundInts)
4 .mapToInt(Integer::parseInt)
5 .sum();
6
7 validator.part1(answer);
8}
9
10private String getBoundInts(String line) {
11 var numbers = line.chars()
12 .filter(Character::isDigit)
13 .mapToObj(Character::toString)
14 .toList();
15
16 return numbers.getFirst() + numbers.getLast();
17}
Part 2
For the second part the assignment becomes slightly more challenging as we also have to keep track of any written out digits, like one and two. To solve this one I added a map with conversions from digits to digits as well as conversions from the written out digits to the digits.
From that point on it is only a matter of eagerly parsing the input using the map to find the first next matching digit.
1public void part2() {
2 var answer = inputLoader.splitOnNewLine()
3 .map(this::parseLine)
4 .mapToInt(Integer::parseInt)
5 .sum();
6
7 validator.part2(answer);
8}
9
10private String parseLine(String line) {
11 var map = new HashMap<String, String>();
12 map.put("1", "1");
13 map.put("2", "2");
14 map.put("3", "3");
15 map.put("4", "4");
16 map.put("5", "5");
17 map.put("6", "6");
18 map.put("7", "7");
19 map.put("8", "8");
20 map.put("9", "9");
21 map.put("one", "1");
22 map.put("two", "2");
23 map.put("three", "3");
24 map.put("four", "4");
25 map.put("five", "5");
26 map.put("six", "6");
27 map.put("seven", "7");
28 map.put("eight", "8");
29 map.put("nine", "9");
30
31 var firstNumber = Optional.<String>empty();
32 var lastNumber = "";
33
34 var parsing = line;
35 while (!parsing.isEmpty()) {
36 for (var entry : map.entrySet()) {
37 if (parsing.startsWith(entry.getKey())) {
38 if (firstNumber.isEmpty()) {
39 firstNumber = Optional.of(entry.getValue());
40 } else {
41 lastNumber = entry.getValue();
42 }
43 break;
44 }
45 }
46
47 parsing = parsing.substring(1);
48 }
49
50 if (lastNumber.isBlank()) {
51 lastNumber = firstNumber.get();
52 }
53
54 return firstNumber.get() + lastNumber;
55}