generated from fspoettel/advent-of-code-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
06.rs
47 lines (40 loc) · 1.37 KB
/
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
advent_of_code::solution!(6);
use ::advent_of_code::{get_nums, get_nums_as_1};
pub fn part_one(input: &str) -> Option<isize> {
let mut lines = input.lines();
let tot_time = get_nums(lines.next().unwrap());
let distance = get_nums(lines.next().unwrap());
let num_races = tot_time.len();
let mut prod = 1;
for i in 0..num_races {
prod *= num_wins(tot_time[i], distance[i]);
}
Some(prod)
}
fn num_wins(tot_time: isize, distance: isize) -> isize {
// quadratic formula
let part = ((tot_time * tot_time - 4 * (-1) * (-distance)) as f64).sqrt();
let higher = ((-tot_time as f64 - part) / -2f64 - 1.0).ceil() as isize;
let lower = ((-tot_time as f64 + part) / -2f64 + 1.0).floor() as isize;
return higher - lower + 1;
}
pub fn part_two(input: &str) -> Option<isize> {
let mut lines = input.lines();
let tot_time = get_nums_as_1(lines.next().unwrap());
let distance = get_nums_as_1(lines.next().unwrap());
Some(num_wins(tot_time, distance))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_part_one() {
let result = part_one(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, Some(288));
}
#[test]
fn test_part_two() {
let result = part_two(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, Some(71503));
}
}