-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday9.rs
72 lines (63 loc) · 1.45 KB
/
day9.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
use aoc_runner_derive::aoc;
fn parse(input: &str) -> Vec<Vec<i32>> {
input
.lines()
.map(|line| {
line.split_whitespace()
.map(|s| s.parse().unwrap())
.collect()
})
.collect()
}
#[aoc(day9, part1)]
#[must_use]
pub fn part1(input: &str) -> i32 {
let input = parse(input);
input
.iter()
.map(|seq| utils::predict_next_recursively(seq))
.sum()
}
#[aoc(day9, part2)]
#[must_use]
pub fn part2(input: &str) -> i32 {
let input = parse(input);
input
.clone()
.iter_mut()
.map(|arr| {
(*arr).reverse();
arr
})
.map(|seq| utils::predict_next_recursively(seq))
.sum()
}
mod utils {
pub fn predict_next_recursively(row: &[i32]) -> i32 {
let next_row: Vec<_> = row.windows(2).map(|w| w[1] - w[0]).collect();
row.last().unwrap()
+ next_row
.iter()
.any(|&number| number != 0)
.then(|| predict_next_recursively(&next_row))
.unwrap_or(0)
}
}
#[cfg(test)]
mod tests {
use super::*;
use indoc::indoc;
const SAMPLE: &str = indoc! {"
0 3 6 9 12 15
1 3 6 10 15 21
10 13 16 21 30 45
"};
#[test]
pub fn part1_example() {
assert_eq!(part1(SAMPLE), 114);
}
#[test]
pub fn part2_example() {
assert_eq!(part2(SAMPLE), 2);
}
}