day6: problem 2 solution

This commit is contained in:
Keenan Tims 2023-12-06 18:15:36 -08:00
parent de6e826c31
commit 9718b8ab04
No known key found for this signature in database
GPG Key ID: B8FDD4AD6B193F06

View File

@ -102,6 +102,8 @@ fn main() {
// PARSER // PARSER
#[derive(Debug)] #[derive(Debug)]
// Appropriate for Problem 1 only
struct Races(Vec<(u64, u64)>); struct Races(Vec<(u64, u64)>);
impl<T: BufRead> From<Lines<T>> for Races { impl<T: BufRead> From<Lines<T>> for Races {
@ -152,12 +154,47 @@ fn problem1_possible_wins(race: (u64, u64)) -> u64 {
fn problem1<T: BufRead>(input: Lines<T>) -> u64 { fn problem1<T: BufRead>(input: Lines<T>) -> u64 {
let races = Races::from(input); let races = Races::from(input);
races.0.iter().map(|race| problem1_possible_wins(*race)).fold(1, |accum, elem| accum * elem) races
.0
.iter()
.map(|race| problem1_possible_wins(*race))
.fold(1, |accum, elem| accum * elem)
} }
// PROBLEM 2 solution // PROBLEM 2 solution
fn problem2<T: BufRead>(input: Lines<T>) -> u64 {
0 // As the race is about to start, you realize the piece of paper with race times and
// record distances you got earlier actually just has very bad kerning. There's really
// only one race - ignore the spaces between the numbers on each line.
// So, the example from before:
// Time: 7 15 30
// Distance: 9 40 200
// ...now instead means this:
// Time: 71530
// Distance: 940200
// Now, you have to figure out how many ways there are to win this single race. In this
// example, the race lasts for 71530 milliseconds and the record distance you need to
// beat is 940200 millimeters. You could hold the button anywhere from 14 to 71516
// milliseconds and beat the record, a total of 71503 ways!
// How many ways can you beat the record in this one much longer race?
fn problem2_parse_all_digits_to_number(s: &str) -> u64 {
s.chars().filter(|c| c.is_digit(10)).fold(0, |accum, elem| {
accum * 10 + elem.to_digit(10).unwrap() as u64
})
}
fn problem2<T: BufRead>(mut input: Lines<T>) -> u64 {
let time = problem2_parse_all_digits_to_number(input.next().unwrap().unwrap().as_str());
let distance = problem2_parse_all_digits_to_number(input.next().unwrap().unwrap().as_str());
problem1_possible_wins((time, distance))
} }
#[cfg(test)] #[cfg(test)]
@ -186,9 +223,9 @@ Distance: 9 40 200";
#[test] #[test]
fn test_possible_wins() { fn test_possible_wins() {
assert_eq!(problem1_possible_wins((7,9)), 4); assert_eq!(problem1_possible_wins((7, 9)), 4);
assert_eq!(problem1_possible_wins((15,40)), 8); assert_eq!(problem1_possible_wins((15, 40)), 8);
assert_eq!(problem1_possible_wins((30,200)), 9); assert_eq!(problem1_possible_wins((30, 200)), 9);
} }
#[test] #[test]
@ -196,4 +233,10 @@ Distance: 9 40 200";
let c = Cursor::new(EXAMPLE); let c = Cursor::new(EXAMPLE);
assert_eq!(problem1(c.lines()), 288); assert_eq!(problem1(c.lines()), 288);
} }
#[test]
fn test_problem2_example() {
let c = Cursor::new(EXAMPLE);
assert_eq!(problem2(c.lines()), 71503);
}
} }