-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathday_06.rs
82 lines (70 loc) · 1.67 KB
/
day_06.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
use common::{solution, Answer};
use itertools::Itertools;
solution!("Wait For It", 6);
fn part_a(input: &str) -> Answer {
parse_a(input)
.iter()
.map(Race::ways_to_win)
.product::<u64>()
.into()
}
fn part_b(input: &str) -> Answer {
parse_b(input).ways_to_win().into()
}
#[derive(Debug)]
struct Race {
time: u64,
distance: u64,
}
fn parse_a(input: &str) -> Vec<Race> {
let (a, b) = input
.lines()
.map(|x| {
x.split_whitespace()
.skip(1)
.map(|x| x.parse::<u64>().unwrap())
})
.next_tuple()
.unwrap();
a.zip(b)
.map(|(time, distance)| Race { time, distance })
.collect::<Vec<_>>()
}
fn parse_b(input: &str) -> Race {
let (time, distance) = input
.lines()
.map(|x| {
x.split_whitespace()
.skip(1)
.collect::<String>()
.parse::<u64>()
.unwrap()
})
.next_tuple()
.unwrap();
Race { time, distance }
}
impl Race {
fn ways_to_win(&self) -> u64 {
let a = ((self.time * self.time - 4 * self.distance) as f32).sqrt();
let x1 = ((self.time as f32 - a) / 2.0 + 1.0).floor();
let x2 = ((self.time as f32 + a) / 2.0 - 1.0).ceil();
(x2 - x1 + 1.0) as u64
}
}
#[cfg(test)]
mod test {
use indoc::indoc;
const CASE: &str = indoc! {"
Time: 7 15 30
Distance: 9 40 200
"};
#[test]
fn part_a() {
assert_eq!(super::part_a(CASE), 288.into());
}
#[test]
fn part_b() {
assert_eq!(super::part_b(CASE), 71503.into());
}
}