AdventOfCode2023/src/solutions/day06.rs

113 lines
2.6 KiB
Rust
Raw Normal View History

2023-12-04 21:21:47 +00:00
use super::Solution;
pub struct Day06 {}
impl Solution for Day06 {
fn part1(
&self,
2023-12-06 12:40:36 +00:00
input: &mut Vec<String>,
2023-12-05 19:33:10 +00:00
) -> Result<Box<dyn std::fmt::Display + Sync>, Box<dyn std::error::Error>> {
2023-12-06 12:40:36 +00:00
let times: Vec<u64> = input[0]
.split_whitespace()
.skip(1)
.map(|t| t.parse().unwrap())
.collect();
let distances: Vec<u64> = input[1]
.split_whitespace()
.skip(1)
.map(|d| d.parse().unwrap())
.collect();
Ok(Box::new(self.num_winning_races(&times, &distances)?))
2023-12-04 21:21:47 +00:00
}
fn part2(
&self,
2023-12-06 12:40:36 +00:00
input: &mut Vec<String>,
2023-12-05 19:33:10 +00:00
) -> Result<Box<dyn std::fmt::Display + Sync>, Box<dyn std::error::Error>> {
2023-12-06 12:40:36 +00:00
let times = vec![input[0]
.split(":")
.nth(1)
.unwrap()
.replace(" ", "")
.parse::<u64>()?];
let distances = vec![input[1]
.split(":")
.nth(1)
.unwrap()
.replace(" ", "")
.parse::<u64>()?];
Ok(Box::new(self.num_winning_races(&times, &distances)?))
2023-12-04 21:21:47 +00:00
}
fn get_day(&self) -> u8 {
2023-12-05 07:25:39 +00:00
6
2023-12-04 21:21:47 +00:00
}
}
2023-12-06 12:40:36 +00:00
impl Day06 {
fn num_winning_races(
&self,
times: &Vec<u64>,
distances: &Vec<u64>,
) -> Result<u32, Box<dyn std::error::Error>> {
let mut beats = vec![];
for (time, record) in times.iter().zip(distances.iter()) {
let mut count: u32 = 0;
for hold in 0..*time {
let dist = (hold) * (time - hold);
if dist > *record {
count += 1;
}
}
beats.push(count);
}
Ok(beats.iter().fold(1, |acc, &b| acc * b))
}
}
2023-12-04 21:21:47 +00:00
/// Test from puzzle input
#[cfg(test)]
mod test {
use super::*;
use crate::*;
#[test]
fn part1() {
let challenge = day06::Day06 {};
//Complete the Challenge
let answer = challenge
.part1(
utils::get_input(challenge.get_day(), utils::InputType::Test1)
.unwrap()
.as_mut(),
)
.unwrap()
.to_string();
2023-12-06 12:40:36 +00:00
assert_eq!(answer, "288");
2023-12-04 21:21:47 +00:00
}
#[test]
fn part2() {
let challenge = day06::Day06 {};
//Complete the Challenge
let answer = challenge
.part2(
utils::get_input(challenge.get_day(), utils::InputType::Test2)
.unwrap()
.as_mut(),
)
.unwrap()
.to_string();
2023-12-06 12:40:36 +00:00
assert_eq!(answer, "71503");
2023-12-04 21:21:47 +00:00
}
}