From e8ea99935e45ae78b4d9e55666ff1dd9c14fdb81 Mon Sep 17 00:00:00 2001 From: BakerNet Date: Fri, 1 Dec 2023 16:07:02 -0800 Subject: [PATCH] day 1 in the books --- data/examples/01.txt | 10 ++++++ src/bin/01.rs | 80 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 90 insertions(+) create mode 100644 data/examples/01.txt create mode 100644 src/bin/01.rs diff --git a/data/examples/01.txt b/data/examples/01.txt new file mode 100644 index 0000000..d407e0e --- /dev/null +++ b/data/examples/01.txt @@ -0,0 +1,10 @@ +1abc2 +pqr3stu8vwx +a1b2c3d4e5f +treb7uchet +two1nine +abcone2threexyz +xtwone3four +4nineeightseven2 +zoneight234 +7pqrstsixteen \ No newline at end of file diff --git a/src/bin/01.rs b/src/bin/01.rs new file mode 100644 index 0000000..497ffc9 --- /dev/null +++ b/src/bin/01.rs @@ -0,0 +1,80 @@ +advent_of_code::solution!(1); + +pub fn part_one(input: &str) -> Option { + Some( + input + .lines() + .map(|line| { + let mut digits = line.char_indices().filter_map(|c| c.1.to_digit(10)); + let first = digits.next().expect("Expected a digit"); + let last = if let Some(last) = digits.last() { + last + } else { + first + }; + first * 10 + last + }) + .sum(), + ) +} + +pub fn part_two(input: &str) -> Option { + Some( + input + .lines() + .map(|line| { + let mut digits = line.char_indices().filter_map(|c| { + if let Some(digit) = c.1.to_digit(10) { + Some(digit) + } else { + if line[c.0..].starts_with("one") { + Some(1) + } else if line[c.0..].starts_with("two") { + Some(2) + } else if line[c.0..].starts_with("three") { + Some(3) + } else if line[c.0..].starts_with("four") { + Some(4) + } else if line[c.0..].starts_with("five") { + Some(5) + } else if line[c.0..].starts_with("six") { + Some(6) + } else if line[c.0..].starts_with("seven") { + Some(7) + } else if line[c.0..].starts_with("eight") { + Some(8) + } else if line[c.0..].starts_with("nine") { + Some(9) + } else { + None + } + } + }); + let first = digits.next().expect("Expected a digit"); + let last = if let Some(last) = digits.last() { + last + } else { + first + }; + first * 10 + last + }) + .sum(), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_part_one() { + let result = part_one(&advent_of_code::template::read_file("examples", DAY)); + assert_eq!(result, Some(142 + 209)); + } + + #[test] + fn test_part_two() { + let result = part_two(&advent_of_code::template::read_file("examples", DAY)); + assert_eq!(result, Some(142 + 198)); + } +}