Compartmentalize part 1 and 2

This commit is contained in:
2023-12-02 01:12:28 +01:00
parent 0db89468f6
commit 704783cfd2

View File

@@ -1,4 +1,53 @@
struct NumberPair(Option<u32>, Option<u32>); pub struct NumberPair(Option<u32>, Option<u32>);
type Approach = Box<dyn Fn(&[char]) -> LineResult>;
type LineResult = NumberPair;
mod part1 {
use super::{Approach, NumberPair};
pub fn approaches() -> Vec<Approach> {
vec![Box::new(|line| {
struct Recorder {
first: Option<u32>,
last: Option<u32>,
}
impl Recorder {
fn new() -> Self {
Self {
first: None,
last: None,
}
}
fn record(&mut self, n: u32) {
if self.first.is_none() {
self.first = Some(n)
} else {
self.last = Some(n)
}
}
fn finish(self) -> NumberPair {
NumberPair(self.first, self.last)
}
}
line.iter()
.fold(Recorder::new(), |mut val, char| {
if let Some(digit) = char.to_digit(10) {
val.record(digit)
}
val
})
.finish()
})]
}
}
mod part2 {
use super::{Approach, NumberPair};
struct SpelledOutNumber(u32); struct SpelledOutNumber(u32);
@@ -37,48 +86,7 @@ fn try_parse_at(input: &[char]) -> Option<u32> {
} }
} }
fn main() { pub fn approaches() -> Vec<Approach> {
let input = std::fs::read_to_string("./input").unwrap();
type Approach = Box<dyn Fn(&[char]) -> NumberPair>;
let parts: [Vec<Approach>; 2] = [
vec![Box::new(|line| {
struct Recorder {
first: Option<u32>,
last: Option<u32>,
}
impl Recorder {
fn new() -> Self {
Self {
first: None,
last: None,
}
}
fn record(&mut self, n: u32) {
if self.first.is_none() {
self.first = Some(n)
} else {
self.last = Some(n)
}
}
fn finish(self) -> NumberPair {
NumberPair(self.first, self.last)
}
}
line.iter()
.fold(Recorder::new(), |mut val, char| {
if let Some(digit) = char.to_digit(10) {
val.record(digit)
}
val
})
.finish()
})],
vec![ vec![
// go through the string one by one, check the value at that position and record it into // go through the string one by one, check the value at that position and record it into
// a `FirstLast` recorder that holds state // a `FirstLast` recorder that holds state
@@ -163,10 +171,14 @@ fn main() {
}, },
) )
}), }),
], ]
]; }
}
let results: [u32; 2] = parts.map(|approaches| { fn main() {
let input = std::fs::read_to_string("./input").unwrap();
let results: [u32; 2] = [part1::approaches(), part2::approaches()].map(|approaches| {
input input
.lines() .lines()
.map(|line| line.chars().collect::<Vec<char>>()) .map(|line| line.chars().collect::<Vec<char>>())