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

1
day1/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
/target

25
day1/Cargo.lock generated Normal file
View file

@ -0,0 +1,25 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "aho-corasick"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b2969dcb958b36655471fc61f7e416fa76033bdd4bfed0678d8fee1e2d07a1f0"
dependencies = [
"memchr",
]
[[package]]
name = "day1"
version = "0.1.0"
dependencies = [
"aho-corasick",
]
[[package]]
name = "memchr"
version = "2.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f665ee40bc4a3c5590afb1e9677db74a508659dfd71e126420da8274909a0167"

9
day1/Cargo.toml Normal file
View file

@ -0,0 +1,9 @@
[package]
name = "day1"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
aho-corasick = "1.1.2"

1000
day1/input Normal file

File diff suppressed because it is too large Load diff

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