Day 1 done

This commit is contained in:
D. Scott Boggs 2023-12-02 07:05:43 -05:00
commit 5dd471795a
5 changed files with 1084 additions and 0 deletions

49
day1/src/main.rs Normal file
View file

@ -0,0 +1,49 @@
use aho_corasick::AhoCorasick;
use std::fs::File;
use std::io::{BufRead, BufReader};
fn main() {
let input = read_input();
let part_1_result = part_1(&input);
let part_2_result = part_2(&input);
println!("Part 1: {part_1_result}");
println!("Part 2: {part_2_result}");
}
fn read_input() -> Vec<String> {
BufReader::new(File::open("input").expect("open input"))
.lines()
.map(|line| line.expect("line"))
.collect()
}
fn part_1(input: &[String]) -> u32 {
input
.iter()
.map(|line| {
let digits: Vec<_> = line.chars().filter_map(|chr| chr.to_digit(10)).collect();
digits[0] * 10 + digits.last().unwrap()
})
.sum()
}
fn part_2(input: &[String]) -> u32 {
let patterns = &[
"one", "1", "two", "2", "three", "3", "four", "4", "five", "5", "six", "6", "seven", "7",
"eight", "8", "nine", "9",
];
let ac = AhoCorasick::new(patterns).unwrap();
input
.iter()
.map(|line| {
let mut matches = ac.find_overlapping_iter(line);
let first = matches.next().expect("first match").pattern().as_u32() / 2 + 1;
let last = if let Some(last) = matches.last() {
last.pattern().as_u32() / 2 + 1
} else {
first
};
first * 10 + last
})
.sum()
}