From 63ce6b5cf20c839f80825a61b30d56d06962e852 Mon Sep 17 00:00:00 2001 From: Dennis Brentjes Date: Thu, 7 Dec 2023 15:34:46 +0100 Subject: [PATCH] I'm dumb. --- src/days/day6.rs | 22 ++++++++++++---------- src/main.rs | 17 +++++++++++------ 2 files changed, 23 insertions(+), 16 deletions(-) diff --git a/src/days/day6.rs b/src/days/day6.rs index d68f8b0..44f9f53 100644 --- a/src/days/day6.rs +++ b/src/days/day6.rs @@ -1,3 +1,4 @@ + use std::{path::Path, str::FromStr, iter::zip}; use itertools::Itertools; @@ -77,22 +78,23 @@ impl FromStr for RecordsOverview { } } +pub fn number_of_record_beating_chances(max_time: i128, record: i128) -> u32 { + let sqrt = ((max_time.pow(2) - 4 * record) as f64).sqrt(); + + let answer1 = -((-max_time as f64) + sqrt) / 2f64; + let answer2 = -((-max_time as f64) - sqrt) / 2f64; + + (answer2.ceil() - answer1.ceil()) as u32 +} + pub fn one() -> Result { let overview = read_into::(Path::new("resources/input6.txt"))?; Ok(overview.records.iter().fold(1, |acc, record| { - acc * ((0..(record.time + 1)).into_iter().map(|x| { - x * (record.time - x) - }).filter(|x| { - *x > record.distance - }).count() as u32) + acc * number_of_record_beating_chances(record.time.into(), record.distance.into()) })) } pub fn two() -> Result { let record = read_into::(Path::new("resources/input6.txt"))?; - Ok((0..(record.time + 1)).into_iter().map(|x| { - x * (record.time - x) - }).filter(|x| { - *x > record.distance - }).count() as u32) + Ok(number_of_record_beating_chances(record.time.into(), record.distance.into())) } \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index 3b9b266..4a30d44 100644 --- a/src/main.rs +++ b/src/main.rs @@ -19,7 +19,7 @@ fn main() -> Result<(), AdventError> { (day6::one as fn() -> Result, day6::two as fn() -> Result), ]; - if env::args().len() != 3 { + if env::args().len() == 1 { Ok(days.into_iter().map(|(one, two)| { let one_result = one()?; let two_result = two()?; @@ -31,11 +31,16 @@ fn main() -> Result<(), AdventError> { }; }).fold((), |acc, _| { acc })) } else { - let (one, two) = days[env::args().nth(1).ok_or(AdventError("Failed to parse day".into()))?.parse::()? - 1]; - match env::args().nth(2).unwrap().parse::()? { - 1 => Ok(println!("1: {}", one()?)), - 2 => Ok(println!("2: {}", two()?)), - _ => return Err(AdventError("part must be either 1 or 2".into())) + let day_index = env::args().nth(1).ok_or(AdventError("Failed to parse day".into()))?.parse::()? - 1; + let (one, two) = days[day_index]; + if env::args().len() == 3 { + match env::args().nth(2).unwrap().parse::()? { + 1 => Ok(println!("1: {}", one()?)), + 2 => Ok(println!("2: {}", two()?)), + _ => return Err(AdventError("part must be either 1 or 2".into())) + } + } else { + Ok(println!("{}: ({}, {})", day_index + 1, one()?, two()?)) } }