From 3f6b917bb3be41f8b9c8a914e44fd5f001713382 Mon Sep 17 00:00:00 2001 From: Reiner Herrmann Date: Fri, 1 Dec 2023 12:00:00 +0100 Subject: day1 solution 1 --- src/bin/day1.rs | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/bin/day1.rs (limited to 'src') diff --git a/src/bin/day1.rs b/src/bin/day1.rs new file mode 100644 index 0000000..4784496 --- /dev/null +++ b/src/bin/day1.rs @@ -0,0 +1,37 @@ +static DAY: u8 = 1; + +fn main() { + let input = advent::read_lines(DAY); + println!("{DAY}a: {}", sum_digits(&input)); + println!("{DAY}b: {}", 0); +} + +fn sum_digits(input: &[String]) -> u32 { + let mut sum = 0; + for line in input { + let left_pos = line.find(|c: char| c.is_digit(10)).expect("line contains digit"); + let right_pos = line.rfind(|c: char| c.is_digit(10)).expect("line contains digit"); + + let line = line.as_bytes(); + let left_digit = (line[left_pos] as char).to_digit(10).unwrap(); + let right_digit = (line[right_pos] as char).to_digit(10).unwrap(); + sum += (left_digit * 10 + right_digit) as u32; + } + sum +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test() { + let input = [ + "1abc2", + "pqr3stu8vwx", + "a1b2c3d4e5f", + "treb7uchet", + ].iter().map(|&x| String::from(x)).collect::>(); + assert_eq!(sum_digits(&input), 142); + } +} -- cgit v1.2.3