generated from fspoettel/advent-of-code-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
09.rs
88 lines (65 loc) · 1.92 KB
/
09.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!(9);
pub fn part_one(input: &str) -> Option<i32> {
let mut sum = 0;
for line in input.lines() {
let interpolated_value = interpolate_sequence(line, Direction::Forward);
sum += interpolated_value;
}
Some(sum)
}
pub fn part_two(input: &str) -> Option<i32> {
let mut sum = 0;
for line in input.lines() {
let interpolated_value = interpolate_sequence(line, Direction::Backward);
sum += interpolated_value;
}
Some(sum)
}
enum Direction {
Forward,
Backward,
}
fn interpolate_sequence(line: &str, direction: Direction) -> i32 {
let mut levels = Vec::new();
let mut current_values = parse_values(line);
while !values_are_zero(¤t_values) {
let next_values = get_derivatives(¤t_values);
levels.push(current_values);
current_values = next_values;
}
let mut interpolated_value = 0;
for values in levels.iter().rev() {
interpolated_value = match direction {
Direction::Forward => values.last().unwrap() + interpolated_value,
Direction::Backward => values.first().unwrap() - interpolated_value,
}
}
interpolated_value
}
fn parse_values(line: &str) -> Vec<i32> {
line.split(' ').map(|s| s.parse().unwrap()).collect()
}
fn get_derivatives(values: &[i32]) -> Vec<i32> {
values
.iter()
.zip(values.iter().skip(1))
.map(|(a, b)| b - a)
.collect()
}
fn values_are_zero(values: &[i32]) -> bool {
values.iter().all(|value| *value == 0)
}
#[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(114));
}
#[test]
fn test_part_two() {
let result = part_two(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, Some(2));
}
}