AoC23/src/day06.rs

81 lines
1.9 KiB
Rust

pub fn run() {
let input = [
Race {
time: 35,
record: 213,
},
Race {
time: 69,
record: 1168,
},
Race {
time: 68,
record: 1086,
},
Race {
time: 87,
record: 1248,
},
];
// example
// let input = [
// Race { time: 7, record: 9 },
// Race {
// time: 15,
// record: 40,
// },
// Race {
// time: 30,
// record: 200,
// },
// ];
let product_of_ways_of_beating_races = input
.iter()
.map(|r| r.count_ways_of_beating_record())
.product::<u64>();
dbg!(product_of_ways_of_beating_races);
let input_combined = Race {
time: 35696887,
record: 213116810861248,
};
// example
// let input_combined = Race {
// time: 71530,
// record: 940200,
// };
dbg!(input_combined.count_ways_of_beating_record());
}
#[derive(Debug, Clone, Copy)]
struct Race {
time: u64,
record: u64,
}
impl Race {
fn count_ways_of_beating_record(&self) -> u64 {
let mut slowest_record_beating_speed = None;
for v in 0..self.time {
if calculate_distance(self.time, v) > self.record {
slowest_record_beating_speed = Some(v);
break;
}
}
let mut fastest_record_beating_speed = None;
for v in (0..self.time).rev() {
if calculate_distance(self.time, v) > self.record {
fastest_record_beating_speed = Some(v);
break;
}
}
fastest_record_beating_speed.unwrap() - slowest_record_beating_speed.unwrap() + 1
}
}
fn calculate_distance(total_time: u64, hold_time: u64) -> u64 {
hold_time * (total_time - hold_time)
}