aoc/year2023/
day01.rs

1//! # Trebuchet?!
2//!
3//! The input can contain overlapping digits such as "twone", so we only remove a letter at a time
4//! until the starting or ending digits are found.
5use crate::util::parse::*;
6
7/// Use the index of each digit as its implicit value.
8const DIGITS: [&[u8]; 9] =
9    [b"one", b"two", b"three", b"four", b"five", b"six", b"seven", b"eight", b"nine"];
10
11pub fn parse(input: &str) -> Vec<&str> {
12    input.lines().collect()
13}
14
15pub fn part1(input: &[&str]) -> u32 {
16    input
17        .iter()
18        .map(|line| {
19            let first = line.bytes().find(u8::is_ascii_digit).unwrap().to_decimal();
20            let last = line.bytes().rfind(u8::is_ascii_digit).unwrap().to_decimal();
21            (10 * first + last) as u32
22        })
23        .sum()
24}
25
26pub fn part2(input: &[&str]) -> usize {
27    input
28        .iter()
29        .map(|line| {
30            let mut line = line.as_bytes();
31
32            let first = 'outer: loop {
33                if line[0].is_ascii_digit() {
34                    break line[0].to_decimal() as usize;
35                }
36                for (value, digit) in DIGITS.iter().enumerate() {
37                    if line.starts_with(digit) {
38                        break 'outer value + 1;
39                    }
40                }
41                line = &line[1..];
42            };
43
44            let last = 'outer: loop {
45                if line[line.len() - 1].is_ascii_digit() {
46                    break line[line.len() - 1].to_decimal() as usize;
47                }
48                for (value, digit) in DIGITS.iter().enumerate() {
49                    if line.ends_with(digit) {
50                        break 'outer value + 1;
51                    }
52                }
53                line = &line[..line.len() - 1];
54            };
55
56            10 * first + last
57        })
58        .sum()
59}