From abb8163f3606733833fda6f01065c6ae72ad8678 Mon Sep 17 00:00:00 2001 From: LordMathis Date: Fri, 1 Dec 2023 17:03:07 +0100 Subject: [PATCH] 2023-01: Implement part 2 --- 2023/01-trebuchet/src/main.rs | 5 ++- 2023/01-trebuchet/src/part_two.rs | 73 +++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+), 2 deletions(-) create mode 100644 2023/01-trebuchet/src/part_two.rs diff --git a/2023/01-trebuchet/src/main.rs b/2023/01-trebuchet/src/main.rs index 0584ac5..e072d03 100644 --- a/2023/01-trebuchet/src/main.rs +++ b/2023/01-trebuchet/src/main.rs @@ -1,6 +1,7 @@ mod part_one; +mod part_two; fn main() { - part_one::part_one(); - //part_two(); + //part_one::part_one(); + part_two::part_two(); } diff --git a/2023/01-trebuchet/src/part_two.rs b/2023/01-trebuchet/src/part_two.rs new file mode 100644 index 0000000..0d8cc08 --- /dev/null +++ b/2023/01-trebuchet/src/part_two.rs @@ -0,0 +1,73 @@ +use std::collections::HashMap; +use std::fs::File; +use std::io::{self, BufRead}; +use std::path::Path; + + +pub fn part_two() { + if let Ok(lines) = read_lines("./input.txt") { + + let mut result = 0; + + for line in lines { + result += parse_line(&line.unwrap()); + } + + println!("{}", result); + } +} + +fn read_lines

(filename: P) -> io::Result>> +where P: AsRef, { + let file = File::open(filename)?; + Ok(io::BufReader::new(file).lines()) +} + +fn parse_line(s: &str) -> u32{ + + const RADIX: u32 = 10; + + let digits : HashMap<&str, u32> = HashMap::from([ + ("one", 1), + ("two", 2), + ("three", 3), + ("four", 4), + ("five", 5), + ("six", 6), + ("seven", 7), + ("eight", 8), + ("nine", 9), + ]); + + let mut first_digit = 0; + let mut last_digit = 0; + + for i in 0..s.len() { + + let c = s.chars().nth(i).unwrap(); + + if c.is_digit(RADIX) { + + let digit = c.to_digit(RADIX).unwrap(); + + if first_digit == 0 { + first_digit = digit; + } + last_digit = digit; + } else { + + for (k, v) in digits.iter() { + if s[i..].starts_with(k) { + + if first_digit == 0 { + first_digit = *v; + } + last_digit = *v; + } + } + + } + } + + return first_digit * 10 + last_digit +} \ No newline at end of file