From b87e0ac219f58f52ba26c1d346fd2c189b2270a6 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sat, 2 Dec 2023 19:20:52 +0100 Subject: [PATCH] day(01): add solution Signed-off-by: Matej Focko --- samples/day01_1.txt | 4 +++ samples/day01_2.txt | 7 +++++ src/bin/day01.rs | 67 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 78 insertions(+) create mode 100644 samples/day01_1.txt create mode 100644 samples/day01_2.txt create mode 100644 src/bin/day01.rs diff --git a/samples/day01_1.txt b/samples/day01_1.txt new file mode 100644 index 0000000..7bbc69a --- /dev/null +++ b/samples/day01_1.txt @@ -0,0 +1,4 @@ +1abc2 +pqr3stu8vwx +a1b2c3d4e5f +treb7uchet diff --git a/samples/day01_2.txt b/samples/day01_2.txt new file mode 100644 index 0000000..41aa89c --- /dev/null +++ b/samples/day01_2.txt @@ -0,0 +1,7 @@ +two1nine +eightwothree +abcone2threexyz +xtwone3four +4nineeightseven2 +zoneight234 +7pqrstsixteen diff --git a/src/bin/day01.rs b/src/bin/day01.rs new file mode 100644 index 0000000..9988174 --- /dev/null +++ b/src/bin/day01.rs @@ -0,0 +1,67 @@ +use aoc_2023::*; + +type Output1 = i32; +type Output2 = Output1; + +const NUMBERS: [&str; 9] = [ + "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", +]; + +struct Day01 { + lines: Vec, +} +impl Solution for Day01 { + fn new>(pathname: P) -> Self { + Self { + lines: file_to_lines(pathname), + } + } + + fn part_1(&mut self) -> Output1 { + self.lines + .iter() + .map(|line| { + let digits = line.chars().filter_map(|c| c.to_digit(10)).collect_vec(); + + (10 * digits.first().unwrap() + digits.last().unwrap()) as i32 + }) + .sum() + } + + fn part_2(&mut self) -> Output2 { + self.lines + .iter() + .map(|line| { + let mut digits: Vec = vec![]; + + for (i, c) in line.chars().enumerate() { + if let Some(d) = c.to_digit(10) { + digits.push(d as i32); + } + + if let Some(d) = NUMBERS + .iter() + .enumerate() + .find_map(|(n, nstr)| { + if line[i..].starts_with(nstr) { + Some(n as i32 + 1) + } else { + None + } + }) + { + digits.push(d) + } + } + + 10 * digits.first().unwrap() + digits.last().unwrap() + }) + .sum() + } +} + +fn main() -> Result<()> { + Day01::main() +} + +test_sample!(day_01, Day01, 142, 281);