Implemented day 6 part 1 and 2 solution
This commit is contained in:
parent
0e95f67099
commit
77caef29a8
2 changed files with 45 additions and 0 deletions
2
input/6.txt
Normal file
2
input/6.txt
Normal file
|
@ -0,0 +1,2 @@
|
|||
Time: 44 80 65 72
|
||||
Distance: 208 1581 1050 1102
|
43
src/bin/day6.rs
Normal file
43
src/bin/day6.rs
Normal file
|
@ -0,0 +1,43 @@
|
|||
fn main() {
|
||||
let input = std::fs::read_to_string("input/6.txt").unwrap();
|
||||
let (result1, result2) = (part1(&input), part2(&input));
|
||||
println!("Day 6");
|
||||
println!("Part 1: {}", result1);
|
||||
println!("Part 2: {}", result2);
|
||||
println!();
|
||||
}
|
||||
|
||||
fn find_hold_time_to_win(time: u64, distance: u64) -> (u64, u64) {
|
||||
let time = time as f64;
|
||||
let winning_distance = (distance + 1) as f64;
|
||||
let discriminant_sqrt = (time * time - 4.0 * winning_distance).sqrt();
|
||||
let (min, max) = ((time - discriminant_sqrt) / 2.0, (time + discriminant_sqrt) / 2.0);
|
||||
let min = (min + 1.0).trunc() as u64;
|
||||
let max = max.trunc() as u64;
|
||||
(min, max)
|
||||
}
|
||||
|
||||
fn part1(input: &str) -> u64 {
|
||||
let (_, times) = input.lines().next().unwrap().split_once(':').unwrap();
|
||||
let times: Vec<u64> = times.trim().split_whitespace().map(|t| t.parse().unwrap()).collect();
|
||||
let (_, distances) = input.lines().last().unwrap().split_once(':').unwrap();
|
||||
let distances: Vec<u64> = distances.trim().split_whitespace().map(|d| d.parse().unwrap()).collect();
|
||||
let times_and_distances: Vec<(u64, u64)> = times.into_iter().zip(distances.into_iter()).collect();
|
||||
let winning_outcomes = times_and_distances.into_iter().map(|(time, distance)| {
|
||||
let (min, max) = find_hold_time_to_win(time, distance);
|
||||
let wins = max - min + 1;
|
||||
wins
|
||||
});
|
||||
winning_outcomes.into_iter().product()
|
||||
}
|
||||
|
||||
fn part2(input: &str) -> u64 {
|
||||
let (_, time) = input.lines().next().unwrap().split_once(':').unwrap();
|
||||
let time: u64 = time.replace(' ', "").parse().unwrap();
|
||||
let (_, distance) = input.lines().last().unwrap().split_once(':').unwrap();
|
||||
let distance: u64 = distance.replace(' ', "").parse().unwrap();
|
||||
let (min, max) = find_hold_time_to_win(time, distance);
|
||||
let wins = max - min + 1;
|
||||
wins
|
||||
}
|
||||
|
Loading…
Reference in a new issue