feat(day6): day6 solution

main
flavien 2023-12-06 19:45:35 +01:00
parent 6c8fdeeeb6
commit cd9515fe0a
No known key found for this signature in database
4 changed files with 70 additions and 1 deletions

View File

@ -26,4 +26,8 @@ path = "src/day4/main.rs"
[[bin]]
name = "day5"
path = "src/day5/main.rs"
path = "src/day5/main.rs"
[[bin]]
name = "day6"
path = "src/day6/main.rs"

2
src/day6/example.txt Normal file
View File

@ -0,0 +1,2 @@
Time: 7 15 30
Distance: 9 40 200

61
src/day6/main.rs Normal file
View File

@ -0,0 +1,61 @@
use adventofcode2023::utils::get_puzzle_bytes;
fn parse_line(line: &[u8]) -> Vec<u64> {
line.split(|&c| c == b' ')
.skip(1)
.filter(|b| !b.is_empty())
.map(|b| atoi::atoi(b).unwrap())
.collect::<Vec<u64>>()
}
fn compute_ways(time: u64, dist: u64) -> u64 {
// first solutiom of quadratic equation
// approximation of minimum time to travel the distance
let x1 = (time - f32::sqrt((time * time - 4 * dist) as f32) as u64) / 2;
// second solutiom of quadratic equation
// approximation of maximum time to travel the distance
let x2 = time - x1;
// longuest distance traveled approximation compared to the real distance for correction
// is the result include of exclude the min/max bounds
let c = (x2 * x1 <= dist) as u64;
x2 - x1 - c * 2 + 1
}
fn count_ways_to_beat_records(puzzle: &[u8]) -> u64 {
let (first_line, second_line) =
puzzle.split_at(puzzle.iter().position(|&c| c == b'\n').unwrap());
let race_times = parse_line(first_line);
let race_distances = parse_line(second_line);
race_times
.into_iter()
.zip(race_distances)
.map(|(time, dist)| compute_ways(time, dist))
.product()
}
fn parse_line_part_2(line: &[u8]) -> u64 {
line.iter()
.filter(|b| b.is_ascii_digit())
.fold(0, |acc, b| acc * 10 + (*b - b'0') as u64)
}
fn count_ways_to_beat_record_part2(puzzle: &[u8]) -> u64 {
let (first_line, second_line) =
puzzle.split_at(puzzle.iter().position(|&c| c == b'\n').unwrap());
let time = parse_line_part_2(first_line);
let dist = parse_line_part_2(second_line);
compute_ways(time, dist)
}
fn main() {
let puzzle = get_puzzle_bytes();
let start_time = std::time::Instant::now();
println!("--- Day 6: Wait For It ---");
println!("What do you get if you multiply these numbers together?");
println!("{}", count_ways_to_beat_records(&puzzle));
println!("--- Part Two ---");
println!("How many ways can you beat the record in this one much longer race?");
println!("{}", count_ways_to_beat_record_part2(&puzzle));
let elapsed_time = start_time.elapsed();
println!("compute time: {:?}", elapsed_time);
}

2
src/day6/puzzle6.txt Normal file
View File

@ -0,0 +1,2 @@
Time: 51 92 68 90
Distance: 222 2031 1126 1225