Last active
December 1, 2023 13:56
-
-
Save johngian/ebd208bebd5e58ef0adb3ab778fa7885 to your computer and use it in GitHub Desktop.
AoC Day 1 - Part 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::fs; | |
use std::io::{BufRead, BufReader}; | |
use std::path::PathBuf; | |
const WORDS: [(&str, u32); 10] = [ | |
("zero", 0), | |
("one", 1), | |
("two", 2), | |
("three", 3), | |
("four", 4), | |
("five", 5), | |
("six", 6), | |
("seven", 7), | |
("eight", 8), | |
("nine", 9), | |
]; | |
fn parse_input(input_path: PathBuf) -> std::io::Lines<std::io::BufReader<std::fs::File>> { | |
let file: fs::File = fs::File::open(input_path).unwrap(); | |
let buf: BufReader<fs::File> = std::io::BufReader::new(file); | |
buf.lines() | |
} | |
fn starts_with_digit(s: &str) -> Option<u32> { | |
let first_char: char = s.chars().next().unwrap(); | |
if first_char.is_numeric() { | |
return Some(first_char.to_digit(10).unwrap()); | |
} | |
for (key, value) in WORDS { | |
if s.starts_with(key) { | |
return Some(value); | |
} | |
} | |
None | |
} | |
fn get_digit(s: &String, reverse: bool) -> Option<u32> { | |
let range = if !reverse { | |
itertools::Either::Left(0..s.len()) | |
} else { | |
itertools::Either::Right((0..=s.len() - 1).rev()) | |
}; | |
for i in range { | |
match starts_with_digit(&s[i..]) { | |
Some(d) => return Some(d), | |
None => continue, | |
} | |
} | |
None | |
} | |
pub fn solve(path: PathBuf) -> u32 { | |
let lines: std::io::Lines<BufReader<fs::File>> = parse_input(path); | |
let mut sum = 0; | |
for line in lines { | |
let l: String = line.unwrap(); | |
sum += 10 * get_digit(&l, false).unwrap() + get_digit(&l, true).unwrap(); | |
} | |
sum | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment