113 lines
2.6 KiB
Rust
113 lines
2.6 KiB
Rust
use super::Solution;
|
|
|
|
pub struct Day06 {}
|
|
|
|
impl Solution for Day06 {
|
|
fn part1(
|
|
&self,
|
|
input: &mut Vec<String>,
|
|
) -> Result<Box<dyn std::fmt::Display + Sync>, Box<dyn std::error::Error>> {
|
|
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(×, &distances)?))
|
|
}
|
|
|
|
fn part2(
|
|
&self,
|
|
input: &mut Vec<String>,
|
|
) -> Result<Box<dyn std::fmt::Display + Sync>, Box<dyn std::error::Error>> {
|
|
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(×, &distances)?))
|
|
}
|
|
|
|
fn get_day(&self) -> u8 {
|
|
6
|
|
}
|
|
}
|
|
|
|
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))
|
|
}
|
|
}
|
|
|
|
/// 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();
|
|
|
|
assert_eq!(answer, "288");
|
|
}
|
|
|
|
#[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();
|
|
|
|
assert_eq!(answer, "71503");
|
|
}
|
|
}
|