day 6 part 2
This commit is contained in:
parent
1d285ee38c
commit
146735881a
1 changed files with 37 additions and 24 deletions
|
@ -30,13 +30,7 @@ fn parser() -> impl Parser<char, Vec<Game>, Error = Simple<char>> {
|
|||
.then_ignore(end())
|
||||
}
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
let games = read("inputs/day6.txt", parser())?;
|
||||
|
||||
let mut result = 1;
|
||||
for game in &games {
|
||||
let t = game.time;
|
||||
let d = game.distance + 1;
|
||||
fn ways2win(t: i64, d: i64) -> i64 {
|
||||
// we want the minimum a s.t. (t-a)*a > d,
|
||||
// and the maximum a s.t. (t-a)*a < d
|
||||
// that means we have a quadratic function -a² + ta - d and we want to find
|
||||
|
@ -44,7 +38,7 @@ fn main() -> anyhow::Result<()> {
|
|||
|
||||
let discriminant = t * t - 4 * d;
|
||||
if discriminant < 0 {
|
||||
continue;
|
||||
return 0;
|
||||
}
|
||||
let sqrt = (discriminant as f64).sqrt();
|
||||
let min = ((t as f64 - sqrt) / 2.0).ceil() as i64;
|
||||
|
@ -56,9 +50,28 @@ fn main() -> anyhow::Result<()> {
|
|||
);
|
||||
assert!(max >= min);
|
||||
|
||||
result *= max - min + 1;
|
||||
max - min + 1
|
||||
}
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
let games = read("inputs/day6.txt", parser())?;
|
||||
|
||||
println!(
|
||||
"{}",
|
||||
games
|
||||
.iter()
|
||||
.map(|game| ways2win(game.time, game.distance))
|
||||
.product::<i64>()
|
||||
);
|
||||
|
||||
let mut t = 0;
|
||||
let mut d = 0;
|
||||
for game in &games {
|
||||
t = t * 10i64.pow((game.time as f64).log10().floor() as u32 + 1) + game.time;
|
||||
d = d * 10i64.pow((game.distance as f64).log10().floor() as u32 + 1)
|
||||
+ game.distance;
|
||||
}
|
||||
println!("{result}");
|
||||
println!("{}", ways2win(t, d));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue