generated from fspoettel/advent-of-code-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path09.rs
103 lines (91 loc) · 2.81 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
use itertools::Itertools;
advent_of_code::solution!(9);
fn parse_and_create_derivatives(
input: &str,
) -> impl Iterator<Item = (Vec<isize>, Vec<Vec<isize>>)> + '_ {
input
.lines()
.map(|line| {
line.split(' ')
.map(|number| number.parse().unwrap())
.collect::<Vec<isize>>()
})
.map(|history| {
let mut derivatives: Vec<Vec<isize>> =
vec![history.iter().tuple_windows().map(|(a, b)| b - a).collect()];
while !derivatives.last().unwrap().iter().all_equal() {
derivatives.push(
derivatives
.last()
.unwrap()
.iter()
.tuple_windows()
.map(|(a, b)| b - a)
.collect(),
);
}
(history, derivatives)
})
}
pub fn part_one(input: &str) -> Option<isize> {
Some(
parse_and_create_derivatives(input)
.map(|(history, derivatives)| {
derivatives
.iter()
.rev()
.chain(std::iter::once(&history))
.map(|derivative| derivative.last().unwrap())
.sum::<isize>()
})
.sum(),
)
}
pub fn part_two(input: &str) -> Option<isize> {
Some(
parse_and_create_derivatives(input)
.map(|(history, derivatives)| {
derivatives
.iter()
.rev()
.chain(std::iter::once(&history))
.map(|derivative| derivative[0])
.fold(0, |acc, last| last - acc)
})
.sum(),
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_part_one() {
let result = part_one(&advent_of_code::template::read_file_part(
"examples", DAY, 1,
));
assert_eq!(result, Some(18));
let result = part_one(&advent_of_code::template::read_file_part(
"examples", DAY, 2,
));
assert_eq!(result, Some(28));
let result = part_one(&advent_of_code::template::read_file_part(
"examples", DAY, 3,
));
assert_eq!(result, Some(68));
}
#[test]
fn test_part_two() {
let result = part_two(&advent_of_code::template::read_file_part(
"examples", DAY, 1,
));
assert_eq!(result, Some(-3));
let result = part_two(&advent_of_code::template::read_file_part(
"examples", DAY, 2,
));
assert_eq!(result, Some(0));
let result = part_two(&advent_of_code::template::read_file_part(
"examples", DAY, 3,
));
assert_eq!(result, Some(5));
}
}