-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday06.rs
88 lines (77 loc) · 2.27 KB
/
day06.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
use aoc_lib::{answer::Answer, solution::Solution};
pub struct Day6;
impl Solution for Day6 {
fn part_a(&self, input: &[String]) -> Answer {
let races = parse_a(input);
races
.iter()
.map(|race| race.count_ways())
.product::<u32>()
.into()
}
fn part_b(&self, input: &[String]) -> Answer {
parse_b(input).count_ways().into()
}
}
struct Race {
duration: u64,
record: u64,
}
fn parse_a(input: &[String]) -> Vec<Race> {
let (_, durations) = input[0].split_once("Time:").unwrap();
let (_, records) = input[1].split_once("Distance:").unwrap();
let durations: Vec<u64> = durations
.split_whitespace()
.map(|t| t.parse::<u64>().unwrap())
.collect();
let records: Vec<u64> = records
.split_whitespace()
.map(|r| r.parse::<u64>().unwrap())
.collect();
let mut races = vec![];
for (&duration, &record) in durations.iter().zip(&records) {
races.push(Race { duration, record });
}
races
}
fn parse_b(input: &[String]) -> Race {
let (_, time) = input[0].split_once("Time:").unwrap();
let (_, record) = input[1].split_once("Distance:").unwrap();
let duration: u64 = time
.split_whitespace()
.collect::<String>()
.parse::<u64>()
.unwrap();
let record: u64 = record
.split_whitespace()
.collect::<String>()
.parse::<u64>()
.unwrap();
Race { duration, record }
}
impl Race {
fn count_ways(&self) -> u32 {
(0..self.duration)
.filter(|e| e * (self.duration - e) > self.record)
.count() as u32
}
}
#[cfg(test)]
mod test {
use aoc_lib::{self, answer::Answer, input, solution::Solution};
use super::Day6;
#[test]
fn test_a() {
let input =
input::read_file(&format!("{}day_06_test.txt", crate::FILES_PREFIX_TEST)).unwrap();
let answer = Day6.part_a(&input);
assert_eq!(<i32 as Into<Answer>>::into(288), answer);
}
#[test]
fn test_b() {
let input =
input::read_file(&format!("{}day_06_test.txt", crate::FILES_PREFIX_TEST)).unwrap();
let answer = Day6.part_b(&input);
assert_eq!(<i32 as Into<Answer>>::into(71503), answer);
}
}