-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.rs
94 lines (81 loc) · 2.59 KB
/
main.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
use nom::{
character::complete::{char, digit1},
combinator::{map_res, opt, recognize},
multi::separated_list1,
sequence::preceded,
Finish, IResult,
};
use rayon::{iter::ParallelIterator, str::ParallelString};
const INPUT: &str = include_str!("input.txt");
// from https://stackoverflow.com/a/74809016
fn integer(input: &str) -> IResult<&str, i32> {
let (i, number) = map_res(recognize(preceded(opt(char('-')), digit1)), |s| {
str::parse(s)
})(input)?;
Ok((i, number))
}
fn history(input: &str) -> IResult<&str, Vec<i32>> {
separated_list1(char(' '), integer)(input)
}
fn a(input: &str) -> i32 {
input
.par_lines()
.map(|line| {
history(line)
.finish()
.map(|(_, history)| history)
.expect("should not be empty 22")
})
.map(|history| {
let mut derivatives = vec![history];
while derivatives.last().unwrap().iter().any(|&i| i != 0) {
let derivative = derivatives
.last()
.expect("should not be empty 30")
.windows(2)
.map(|l| l.last().expect("should not be empty 32") - l.first().unwrap())
.collect::<Vec<_>>();
derivatives.push(derivative)
}
derivatives
.iter()
.rev()
.map(|derivative| derivative.last().expect("should not be empty 41"))
.sum::<i32>()
})
.sum()
}
fn b(input: &str) -> i32 {
input
.par_lines()
.map(|line| {
history(line)
.finish()
.map(|(_, history)| history)
.expect("should not be empty 22")
})
.map(|history| {
let mut derivatives = vec![history];
while derivatives.last().unwrap().iter().any(|&i| i != 0) {
let derivative = derivatives
.last()
.expect("should not be empty 30")
.windows(2)
.map(|l| l.last().expect("should not be empty 32") - l.first().unwrap())
.collect::<Vec<_>>();
derivatives.push(derivative)
}
derivatives
.iter()
.rev()
.map(|derivative| derivative.first().expect("should not be empty 41"))
.fold(0, |acc, curr| curr - acc)
})
.sum()
}
fn main() {
let sum = a(INPUT);
println!("{sum}");
let sum = b(INPUT);
println!("{sum}");
}