2023-01: Implement part 2

This commit is contained in:
LordMathis 2023-12-01 17:03:07 +01:00
parent d6382ce487
commit abb8163f36
2 changed files with 76 additions and 2 deletions

View File

@ -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();
}

View File

@ -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<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where P: AsRef<Path>, {
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
}