I am participating in this year's Advent of Code for fun.
Challenge 1.2 states:
The newly-improved calibration document consists of lines of text; each line originally contained a specific calibration value that the Elves now need to recover. On each line, the calibration value can be found by combining the first digit and the last digit (in that order) to form a single two-digit number.
--- Part Two ---
Your calculation isn't quite right. It looks like some of the digits are actually spelled out with letters: one, two, three, four, five, six, seven, eight, and nine also count as valid "digits".
Equipped with this new information, you now need to find the real first and last digit on each line. For example:
eightwothree abcone2threexyz xtwone3four 4nineeightseven2 zoneight234 7pqrstsixteen
In this example, the calibration values are 29, 83, 13, 24, 42, 14, and 76. Adding these together produces 281.
What is the sum of all of the calibration values?
Cargo.toml
[package]
name = "aoc1_2"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
clap = { version = "4.4.10", features = ["derive"] }
env_logger = "0.10.1"
log = "0.4.20"
lib.rs
const DIGIT_NAMES: [&str; 9] = [
"one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
];
#[must_use]
pub fn two_digit_number(line: &str) -> Option<u8> {
let mut digits = Digits::new(line);
let first_digit = digits.next()?;
let mut number = String::from(first_digit);
if let Some(last_digit) = digits.last() {
number.push(last_digit);
} else {
number.push(first_digit);
}
number.parse().ok()
}
#[derive(Debug)]
struct Digits<'a> {
text: &'a str,
size: usize,
start: usize,
end: usize,
}
impl<'a> Digits<'a> {
#[must_use]
pub fn new(text: &'a str) -> Self {
Self {
text,
size: text.chars().count(),
start: 0,
end: 0,
}
}
}
impl<'a> Iterator for Digits<'a> {
type Item = char;
fn next(&mut self) -> Option<Self::Item> {
if self.start == self.size {
return None;
}
if self.end > self.size {
self.start += 1;
self.end = self.start + 1;
return self.next();
}
match is_digit(&self.text[self.start..self.end]) {
IsDigit::Yes(digit) => {
self.end += 1;
Some(digit)
}
IsDigit::Maybe => {
self.end += 1;
self.next()
}
IsDigit::No => {
self.start += 1;
self.end = self.start + 1;
self.next()
}
}
}
}
fn is_digit(text: &str) -> IsDigit {
if text.len() == 1 {
if let Some(chr) = text.chars().next() {
if chr.is_ascii_digit() {
return IsDigit::Yes(chr);
}
}
}
match text {
"one" => IsDigit::Yes('1'),
"two" => IsDigit::Yes('2'),
"three" => IsDigit::Yes('3'),
"four" => IsDigit::Yes('4'),
"five" => IsDigit::Yes('5'),
"six" => IsDigit::Yes('6'),
"seven" => IsDigit::Yes('7'),
"eight" => IsDigit::Yes('8'),
"nine" => IsDigit::Yes('9'),
text => {
if DIGIT_NAMES.iter().any(|name| name.starts_with(text)) {
IsDigit::Maybe
} else {
IsDigit::No
}
}
}
}
#[derive(Debug, Eq, PartialEq)]
pub enum IsDigit {
Yes(char),
Maybe,
No,
}
#[cfg(test)]
mod tests {
use crate::two_digit_number;
const LINES: [(&str, u8); 7] = [
("two1nine", 29),
("eightwothree", 83),
("abcone2threexyz", 13),
("xtwone3four", 24),
("4nineeightseven2", 42),
("zoneight234", 14),
("7pqrstsixteen", 76),
];
#[test]
fn test_lines() {
for (line, number) in LINES {
assert_eq!(two_digit_number(line), Some(number));
}
}
}
main.rs
use aoc1_2::two_digit_number;
use clap::Parser;
use log::{error, warn};
use std::fs::read_to_string;
use std::path::PathBuf;
use std::process::exit;
#[derive(Debug, Parser)]
pub struct Args {
#[arg(index = 1)]
input: PathBuf,
}
impl Args {
#[must_use]
pub fn input(&self) -> String {
read_to_string(&self.input).unwrap_or_else(|error| {
error!("{error}");
exit(1);
})
}
}
fn main() {
env_logger::init();
let args = Args::parse();
let mut sum: u64 = 0;
for line in args.input().lines() {
two_digit_number(line).map_or_else(
|| {
warn!("No number in: {line}");
},
|number| {
sum += u64::from(number);
},
);
}
println!("The sum is: {sum}");
}
I don't like the fact, that I have the digit names twice, once in an array and once in the match statement. How can I improve the code?
…, ("eightwo", 82), ("oneightsevenine", 19), …
\$\endgroup\$