From 250f0e163c470a4492c075f5342a329b2d4950e0 Mon Sep 17 00:00:00 2001 From: Lennard Brinkhaus Date: Wed, 6 Dec 2023 16:51:30 +0100 Subject: [PATCH] refactor: day 6 is now more performant --- src/day05.rs | 3 ++- src/day06.rs | 35 +++++++++++++++++++---------------- 2 files changed, 21 insertions(+), 17 deletions(-) diff --git a/src/day05.rs b/src/day05.rs index b152943..e348812 100644 --- a/src/day05.rs +++ b/src/day05.rs @@ -1,4 +1,5 @@ -use std::collections::{HashMap}; +#![allow(dead_code)] + use std::time::Instant; use itertools::Itertools; use rayon::prelude::*; diff --git a/src/day06.rs b/src/day06.rs index e1c3e7f..48f43cf 100644 --- a/src/day06.rs +++ b/src/day06.rs @@ -1,3 +1,4 @@ +use std::ops::Range; use std::time::Instant; pub fn execute_task01(content: &str) { @@ -18,7 +19,7 @@ pub fn execute_task02(content: &str) { println!("Day06 - Task02 - Duration: {duration:?} - Correct Race: {}", product_correct_races) } -fn solve_01(content: &str) -> anyhow::Result { +fn solve_01(content: &str) -> anyhow::Result { let result = content .lines() .map(|line| line @@ -42,11 +43,11 @@ fn solve_01(content: &str) -> anyhow::Result { Ok(races .iter() .map(|(time, distance)| calc_possible_options(*time, *distance)) - .map(|options| options.len()) + .map(|options| options.end - options.start) .product()) } -fn solve_02(content: &str) -> anyhow::Result { +fn solve_02(content: &str) -> anyhow::Result { let result = content .lines() .map(|line| line @@ -63,24 +64,26 @@ fn solve_02(content: &str) -> anyhow::Result { Ok(races .iter() .map(|(time, distance)| calc_possible_options(*time, *distance)) - .map(|options| options.len()) + .map(|options| options.end - options.start) .product()) } -fn calc_possible_options(time: i64, distance: i64) -> Vec { - let mut data = vec![]; - // TODO Performance!!! - for i in 1..time { - let y = i * (time - i); - if y > distance { - data.push(i) - } else if data.len() > 0 { - break - } - } +fn calc_possible_options(time: i64, distance: i64) -> Range { + // f(x) = x * (time - x) + // f(x) = time * x - x * x + // PQ Ready: 0 = x * x - time * x + distance + // => + // p = - time + // q = distance - data + let time = time as f64; + let distance = distance as f64; + + let x1 = time / 2.0 - ((time * time / 4.0) - distance).sqrt(); + let x2 = time / 2.0 + ((time * time / 4.0) - distance).sqrt(); + + (x1.floor() as i64 + 1)..(x2.ceil() as i64) } #[test]