-
Notifications
You must be signed in to change notification settings - Fork 0
/
d9.rs
58 lines (52 loc) · 1.51 KB
/
d9.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
#![allow(clippy::must_use_candidate, clippy::missing_panics_doc)]
use itertools::Itertools;
fn build_differences(line: &str) -> Vec<Vec<i64>> {
let values = line
.split_whitespace()
.map(|value| value.parse::<i64>().unwrap())
.collect::<Vec<_>>();
std::iter::successors(Some(values), |values| {
Some(
values
.iter()
.tuple_windows()
.map(|(a, b)| b - a)
.collect::<Vec<_>>(),
)
})
.take_while(|values| values.iter().any(|value| *value != 0))
.collect::<Vec<_>>()
}
pub fn part1(input: &str) -> i64 {
input
.lines()
.map(|line| {
build_differences(line)
.iter()
.rev()
.fold(0, |extrapolated, values| {
let last_value = values.last().unwrap();
extrapolated + last_value
})
})
.sum()
}
pub fn part2(input: &str) -> i64 {
input
.lines()
.map(|line| {
build_differences(line)
.iter()
.rev()
.fold(0, |extrapolated, values| {
let first_value = values.first().unwrap();
first_value - extrapolated
})
})
.sum()
}
pub fn main() {
let input = std::fs::read_to_string("../../input/9.txt").expect("Input file not found");
println!("Part 1 : {}", part1(&input));
println!("Part 2 : {}", part2(&input));
}