generated from fspoettel/advent-of-code-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
06.rs
88 lines (70 loc) · 1.95 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
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
advent_of_code::solution!(6);
use advent_of_code::maneatingape::parse::*;
struct Race {
time: u64,
distance: u64,
}
fn parse_data(input: &str) -> Vec<Race> {
let (time, distance) = input.split_once('\n').unwrap();
time.iter_unsigned()
.zip(distance.iter_unsigned())
.map(|(time, distance)| Race { time, distance })
.collect()
}
fn part_x(race: Race) -> u64 {
let mut a = 0;
let mut b = race.time / 2;
loop {
let c = (a + b) / 2;
if c * (race.time - c) > race.distance && (c - 1) * (race.time - c + 1) <= race.distance {
break c;
}
if c * (race.time - c) <= race.distance {
a = c;
} else {
b = c;
}
}
}
pub fn part_one(input: &str) -> Option<u64> {
let races = parse_data(input);
let result = races
.into_iter()
.map(|race| (race.time, part_x(race)))
.map(|(time, best_time)| time - best_time - best_time + 1)
.product::<u64>();
Some(result)
}
pub fn part_two(input: &str) -> Option<u64> {
let races = parse_data(input);
let time = races
.iter()
.map(|race| race.time)
.fold(String::new(), |acc, x| acc + &x.to_string())
.as_str()
.unsigned();
let distance = races
.iter()
.map(|race| race.distance)
.fold(String::new(), |acc, x| acc + &x.to_string())
.as_str()
.unsigned();
let race = Race { time, distance };
let best_time = part_x(race);
let result = time - best_time - best_time + 1;
Some(result)
}
#[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));
}
}