|
1 |
| -using System; |
2 | 1 | using System.Linq;
|
| 2 | +using System.Text.RegularExpressions; |
3 | 3 |
|
4 | 4 | namespace AdventOfCode.Y2023.Day01;
|
5 | 5 |
|
6 | 6 | [ProblemName("Trebuchet?!")]
|
7 | 7 | class Solution : Solver {
|
8 | 8 |
|
9 | 9 | public object PartOne(string input) =>
|
10 |
| - Solve(input, Digit); |
| 10 | + Solve(input, @"\d"); |
11 | 11 |
|
12 | 12 | public object PartTwo(string input) =>
|
13 |
| - Solve(input, st => Digit(st) ?? SpelledOutNumber(st)); |
| 13 | + Solve(input, @"\d|one|two|three|four|five|six|seven|eight|nine"); |
14 | 14 |
|
15 |
| - int? Digit(string st) => char.IsDigit(st[0]) ? st[0] - '0' : null; |
| 15 | + int Solve(string input, string rx) => |
| 16 | + input.Split("\n").Select(line => GetNumber(line, rx)).Sum(); |
| 17 | + |
| 18 | + int GetNumber(string line, string rx) { |
| 19 | + var first = Regex.Match(line, rx); |
| 20 | + var last = Regex.Match(line, rx, RegexOptions.RightToLeft); |
16 | 21 |
|
17 |
| - int? SpelledOutNumber(string st) => |
18 |
| - st.StartsWith("one") ? 1 : |
19 |
| - st.StartsWith("two") ? 2 : |
20 |
| - st.StartsWith("three") ? 3 : |
21 |
| - st.StartsWith("four") ? 4 : |
22 |
| - st.StartsWith("five") ? 5 : |
23 |
| - st.StartsWith("six") ? 6 : |
24 |
| - st.StartsWith("seven") ? 7 : |
25 |
| - st.StartsWith("eight") ? 8 : |
26 |
| - st.StartsWith("nine") ? 9 : |
27 |
| - null; |
28 |
| - |
29 |
| - int Solve(string input, Func<string, int?> parser) => |
30 |
| - input.Split("\n").Select(line => GetNumber(line, parser)).Sum(); |
31 |
| - |
32 |
| - // Go over the line from both ends using the parser and find the first numbers |
33 |
| - // in both directions, these will be the "first" and "last" digits. |
34 |
| - // Returns 0 if no numbers found. |
35 |
| - int GetNumber(string line, Func<string, int?> parse) { |
36 |
| - int? first = null; |
37 |
| - int? last = null; |
38 |
| - |
39 |
| - for (var i =0; i < line.Length; i++) { |
40 |
| - var prefix = line[i..]; |
41 |
| - first = first ?? parse(prefix); |
42 |
| - |
43 |
| - var suffix = line[(line.Length - i - 1)..]; |
44 |
| - last = last ?? parse(suffix); |
45 |
| - |
46 |
| - if (first.HasValue && last.HasValue) { |
47 |
| - return first.Value * 10 + last.Value; |
48 |
| - } |
49 |
| - } |
50 |
| - return 0; |
| 22 | + return ParseMatch(first) * 10 + ParseMatch(last); |
51 | 23 | }
|
| 24 | + |
| 25 | + int ParseMatch(Match m) => |
| 26 | + !m.Success ? 0 : |
| 27 | + m.Groups[0].Value == "one" ? 1 : |
| 28 | + m.Groups[0].Value == "two" ? 2 : |
| 29 | + m.Groups[0].Value == "three" ? 3 : |
| 30 | + m.Groups[0].Value == "four" ? 4 : |
| 31 | + m.Groups[0].Value == "five" ? 5 : |
| 32 | + m.Groups[0].Value == "six" ? 6 : |
| 33 | + m.Groups[0].Value == "seven" ? 7 : |
| 34 | + m.Groups[0].Value == "eight" ? 8 : |
| 35 | + m.Groups[0].Value == "nine" ? 9 : |
| 36 | + int.Parse(m.Groups[0].Value); |
52 | 37 | }
|
0 commit comments