generated from fspoettel/advent-of-code-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path09.rs
54 lines (49 loc) · 1.42 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
use advent_of_code::get_nums;
advent_of_code::solution!(9);
pub fn part_one(input: &str) -> Option<isize> {
let sum = input
.lines()
.map(|line| {
let mut nums = get_nums(line);
let mut ends = nums[nums.len() - 1];
// while nums is not all zeroes
while !nums.iter().all(|&e| e == 0) {
nums = nums.windows(2).map(|pair| pair[1] - pair[0]).collect();
ends += nums[nums.len() - 1];
}
ends
})
.sum();
Some(sum)
}
pub fn part_two(input: &str) -> Option<isize> {
let sum = input
.lines()
.map(|line| {
let mut nums = get_nums(line);
nums.reverse();
let mut ends = nums[nums.len() - 1];
// while nums is not all zeroes
while !nums.iter().all(|&e| e == 0) {
nums = nums.windows(2).map(|pair| pair[1] - pair[0]).collect();
ends += nums[nums.len() - 1];
}
ends
})
.sum();
Some(sum)
}
#[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));
}
}