From 46cee023d2c7473095b65a543076cc1d40d9ab80 Mon Sep 17 00:00:00 2001 From: "Adam T. Carpenter" Date: Mon, 4 Dec 2023 13:51:38 +0000 Subject: chore: common repo chore: break out part a chore: refactor to include b mode flag finish day 2 ignore --- aoc01/src/main.rs | 58 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 aoc01/src/main.rs (limited to 'aoc01/src/main.rs') diff --git a/aoc01/src/main.rs b/aoc01/src/main.rs new file mode 100644 index 0000000..62db893 --- /dev/null +++ b/aoc01/src/main.rs @@ -0,0 +1,58 @@ +use std::{env::args, io::stdin}; + +const NUM_WORDS: [(&str, &str); 9] = [ + ("one", "1"), + ("two", "2"), + ("three", "3"), + ("four", "4"), + ("five", "5"), + ("six", "6"), + ("seven", "7"), + ("eight", "8"), + ("nine", "9"), +]; + +fn word_to_digit(word: &str) -> &str { + match word { + "one" => "1", + "two" => "2", + "three" => "3", + "four" => "4", + "five" => "5", + "six" => "6", + "seven" => "7", + "eight" => "8", + "nine" => "9", + num => num, + } +} + +fn get_digits(line: &str) -> u32 { + let mut found = Vec::new(); + let find_words = args().any(|b| b == "-b"); + + for (word, num) in NUM_WORDS { + found.extend(line.match_indices(num)); + + if find_words { + found.extend(line.match_indices(word)); + } + } + + found.sort(); + + let first = word_to_digit(found.first().unwrap().1); + let last = word_to_digit(found.last().unwrap().1); + + let combined = format!("{first}{last}"); + combined.parse().unwrap() +} + +fn main() { + let i: u32 = stdin() + .lines() + .filter_map(|l| Some(get_digits(&l.ok()?))) + .sum(); + + println!("{i}"); +} -- cgit v1.2.3