From 691b44d1e91740a3fe813ceea1bb5e3f13e7d06f Mon Sep 17 00:00:00 2001 From: Niklas Kapelle Date: Wed, 13 Dec 2023 16:10:14 +0100 Subject: [PATCH] day 6 --- input/6.txt | 2 ++ src/common.rs | 22 +++++++++++++++++++-- src/main.rs | 3 +++ src/six.rs | 54 +++++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 79 insertions(+), 2 deletions(-) create mode 100644 input/6.txt create mode 100644 src/six.rs diff --git a/input/6.txt b/input/6.txt new file mode 100644 index 0000000..a15dea2 --- /dev/null +++ b/input/6.txt @@ -0,0 +1,2 @@ +Time: 62 64 91 90 +Distance: 553 1010 1473 1074 \ No newline at end of file diff --git a/src/common.rs b/src/common.rs index 4d7efa6..d0d4f32 100644 --- a/src/common.rs +++ b/src/common.rs @@ -1,5 +1,10 @@ -use std::{fs::File, io::{BufReader, BufRead}}; +use std::{ + fs::File, + io::{BufRead, BufReader}, + str::FromStr, +}; +use regex::Regex; pub fn load_input(filepath: &str) -> Result, Box> { let file = File::open(filepath)?; @@ -13,4 +18,17 @@ pub fn load_input(filepath: &str) -> Result, Box(s: &str) -> Vec +where + T: FromStr, +{ + let regex = Regex::new(r"(?m)(\d+)").unwrap(); + let result = regex.captures_iter(s); + + result + .map(|e| e.get(0).unwrap().as_str()) + .flat_map(|e| e.parse::()) + .collect() +} diff --git a/src/main.rs b/src/main.rs index 540350e..ef65f33 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,6 +6,7 @@ mod two; mod three; mod four; mod five; +mod six; fn main() { let args: Vec = env::args().collect(); @@ -22,6 +23,8 @@ fn main() { "4p2" => four::run_part2(), "5" => five::run(), "5p2" => five::run_part2(), + "6" => six::run(), + "6p2" => six::run_part2(), _ => Ok(-1), }; diff --git a/src/six.rs b/src/six.rs new file mode 100644 index 0000000..baec2fc --- /dev/null +++ b/src/six.rs @@ -0,0 +1,54 @@ +use crate::common::{load_input, parse_nums}; + +fn parse_input(lines: &[String]) -> (Vec, Vec) { + ( + parse_nums(lines.get(0).unwrap()), + parse_nums(lines.get(1).unwrap()), + ) +} + +fn distance_by_time_pressed(time_pressed: u64, race_time: u64) -> u64 { + let speed = (race_time - time_pressed); + return speed * time_pressed; +} + +fn join_nums(nums: &[u64]) -> u64 { + nums.iter() + .map(|e| e.to_string()) + .collect::() + .parse() + .unwrap() +} + +pub fn run_part2() -> Result> { + let lines = load_input("./input/6.txt")?; + let (time, distance) = parse_input(&lines); + let new_time = join_nums(&time); + let new_dist = join_nums(&distance); + + let res = (0..new_time) + .map(|pressed| distance_by_time_pressed(pressed, new_time)) + .filter(|e| *e > new_dist) + .count(); + + Ok(res.try_into().unwrap()) +} + +pub fn run() -> Result> { + let lines = load_input("./input/6.txt")?; + let (time, distance) = parse_input(&lines); + + let res = time + .iter() + .zip(distance.iter()) + .map(|e| { + (0..*e.0) + .map(|pressed| distance_by_time_pressed(pressed, *e.0)) + .filter(|dist| *dist > *e.1) + .count() + }) + .reduce(|acc, e| e * acc) + .unwrap(); + + Ok(res.try_into().unwrap()) +}