-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02.rs
More file actions
93 lines (79 loc) · 2.18 KB
/
02.rs
File metadata and controls
93 lines (79 loc) · 2.18 KB
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
advent_of_code::solution!(2);
use itertools::Itertools;
type Report = Vec<u32>;
type Input = Vec<Report>;
pub fn parse(input: &str) -> Input {
input
.lines()
.map(|s| {
s.split_whitespace()
.map(|s| s.parse::<u32>().unwrap())
.collect_vec()
})
.collect_vec()
}
pub fn check_safety(report: &Report) -> bool {
let increasing_or_decreasing_satisfied = report
.windows(2)
.flat_map(<&[u32; 2]>::try_from)
.all(|[left, right]| left <= right)
|| report
.windows(2)
.flat_map(<&[u32; 2]>::try_from)
.all(|[left, right]| left >= right);
if !increasing_or_decreasing_satisfied {
return false;
};
report
.windows(2)
.flat_map(<&[u32; 2]>::try_from)
.all(|[left, right]| {
let diff = left.abs_diff(*right);
diff >= 1 && diff <= 3
})
}
pub fn part_one(input: &str) -> Option<u32> {
let parsed_input = parse(input);
let answer = parsed_input
.iter()
.filter(|report| check_safety(&report))
.count();
Some(answer as u32)
}
pub fn part_two(input: &str) -> Option<u32> {
let parsed_input = parse(input);
let answer = parsed_input
.iter()
.filter(|report| {
if check_safety(&report) {
true
} else {
for i in 0..report.len() {
let mut new_report = (*report).clone();
new_report.remove(i);
return if check_safety(&new_report) {
true
} else {
continue;
};
}
return false;
}
})
.count();
Some(answer as u32)
}
#[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(2));
}
#[test]
fn test_part_two() {
let result = part_two(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, Some(4));
}
}