refactor: day 6 is now more performant
This commit is contained in:
parent
39aa33152f
commit
250f0e163c
@ -1,4 +1,5 @@
|
||||
use std::collections::{HashMap};
|
||||
#![allow(dead_code)]
|
||||
|
||||
use std::time::Instant;
|
||||
use itertools::Itertools;
|
||||
use rayon::prelude::*;
|
||||
|
35
src/day06.rs
35
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<usize> {
|
||||
fn solve_01(content: &str) -> anyhow::Result<i64> {
|
||||
let result = content
|
||||
.lines()
|
||||
.map(|line| line
|
||||
@ -42,11 +43,11 @@ fn solve_01(content: &str) -> anyhow::Result<usize> {
|
||||
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<usize> {
|
||||
fn solve_02(content: &str) -> anyhow::Result<i64> {
|
||||
let result = content
|
||||
.lines()
|
||||
.map(|line| line
|
||||
@ -63,24 +64,26 @@ fn solve_02(content: &str) -> anyhow::Result<usize> {
|
||||
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<i64> {
|
||||
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<i64> {
|
||||
// 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]
|
||||
|
Loading…
Reference in New Issue
Block a user