[TWEAK] Day 6 is now solved with math, making it a lot faster
This commit is contained in:
21
src/day6.rs
21
src/day6.rs
@@ -1,5 +1,5 @@
|
|||||||
use num::integer::sqrt;
|
|
||||||
use num::ToPrimitive;
|
use num::ToPrimitive;
|
||||||
|
|
||||||
use crate::day_solver::DaySolver;
|
use crate::day_solver::DaySolver;
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
use crate::util::read_file;
|
use crate::util::read_file;
|
||||||
@@ -30,13 +30,18 @@ impl Day6 {
|
|||||||
|
|
||||||
fn calc_ways_to_beat(time: u64, dist: u64) -> u64 {
|
fn calc_ways_to_beat(time: u64, dist: u64) -> u64 {
|
||||||
|
|
||||||
let mut records_this_race = 0u64;
|
// y = (t - x) * x = tx - x^2
|
||||||
for pressed in 0..time {
|
// We need to solve for tx - x^2 = d
|
||||||
if Day6::calc_dist(time, pressed) > dist {
|
// Solve for x:
|
||||||
records_this_race += 1;
|
// x = (t - sqrt(t^2 -4d)) / 2
|
||||||
}
|
// x = (sqrt(t^2 -4d) + t) / 2
|
||||||
}
|
// Difference between those two solutions is the answer
|
||||||
return records_this_race
|
|
||||||
|
let time_f = time.to_f64().unwrap();
|
||||||
|
let dist_f = dist.to_f64().unwrap();
|
||||||
|
let min_win = (time_f - f64::sqrt(time_f * time_f - 4f64 * dist_f)) / 2f64;
|
||||||
|
let max_win = (f64::sqrt(time_f * time_f - 4f64 * dist_f) + time_f) / 2f64;
|
||||||
|
return f64::floor(max_win).to_u64().unwrap() - f64::ceil(min_win).to_u64().unwrap() + 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user