advent_of_code_2023_in_rust/src/solutions/day6/parsing.rs
2024-08-18 15:03:45 +02:00

67 lines
2.2 KiB
Rust

use super::{race_record::RaceRecord, NumericValue};
pub fn parsing(input: &str) -> Vec<RaceRecord> {
let mut must_be_2_lines = input.lines().take(2);
match (must_be_2_lines.next(), must_be_2_lines.next()) {
(Some(first_line), Some(second_line)) => {
let stripped_first = first_line.strip_prefix("Time:").unwrap();
let stripped_second = second_line.strip_prefix("Distance:").unwrap();
let splitted_first = stripped_first
.split_whitespace()
.map(|to_parse| to_parse.parse::<NumericValue>().unwrap());
let splitted_second = stripped_second
.split_whitespace()
.map(|to_parse| to_parse.parse::<NumericValue>().unwrap());
splitted_first
.zip(splitted_second)
.map(|(time, distance)| RaceRecord::new(time, distance))
.collect()
}
_ => unreachable!(),
}
}
pub fn parsing_part_2(input: &str) -> RaceRecord {
let (time_str, reached_str) = parsing(input)
.into_iter()
.map(|record| {
(
record.time().to_string(),
record.reached_distance().to_string(),
)
})
.fold(
(String::new(), String::new()),
|(acc_time_str, acc_reached_str), (time_str, distance_str)| {
(acc_time_str + &time_str, acc_reached_str + &distance_str)
},
);
RaceRecord::new(time_str.parse().unwrap(), reached_str.parse().unwrap())
}
#[cfg(test)]
mod testing {
use crate::solutions::day6::race_record::RaceRecord;
#[test]
fn should_parse() {
let input = include_str!("day_example_input.txt");
let parsed = super::parsing(input);
let expected = vec![
RaceRecord::new(7, 9),
RaceRecord::new(15, 40),
RaceRecord::new(30, 200),
];
assert_eq!(expected, parsed);
}
#[test]
fn should_parse_part_2() {
let input = include_str!("day_example_input.txt");
let parsed = super::parsing_part_2(input);
let expected = RaceRecord::new(71530, 940200);
assert_eq!(expected, parsed);
}
}