-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday02.rs
More file actions
51 lines (39 loc) · 1.03 KB
/
Copy pathday02.rs
File metadata and controls
51 lines (39 loc) · 1.03 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
//! Red-Nosed Reports
//!
//! Summary:
pub fn parse(input: &str) -> &str {
input.trim()
}
pub fn part1(input: &str) -> u32 {
solve(input, false)
}
pub fn part2(input: &str) -> u32 {
solve(input, true)
}
fn solve(input: &str, part2: bool) -> u32 {
let mut ans = 0;
for line in input.lines() {
let report: Vec<i32> = line.split_whitespace().map(|v| v.parse::<i32>().unwrap()).collect();
if is_safe(&report) {
ans += 1;
continue;
}
if !part2 {
continue;
}
for i in 0..report.len() {
let mut report_tol = report.clone();
report_tol.remove(i);
if is_safe(&report_tol) {
ans += 1;
break;
}
}
}
ans
}
fn is_safe(report: &[i32]) -> bool {
let diffs: Vec<i32> = report.windows(2).map(|pair| pair[0] - pair[1]).collect();
(diffs.iter().all(|v| v > &0) || diffs.iter().all(|v| v < &0))
&& diffs.iter().map(|&x| x.abs()).max().unwrap() <= 3
}