-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday02.rs
82 lines (63 loc) · 1.7 KB
/
day02.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
use std::fmt::Display;
use crate::days::Day;
pub struct Day02;
impl Day for Day02 {
fn part_one(input: &str) -> impl Display {
let mut safe_sum = 0;
for line in input.lines() {
let report = line
.split_whitespace()
.map(|num: &str| num.parse().unwrap())
.collect();
if is_safe(&report) {
safe_sum += 1;
}
}
safe_sum
}
fn part_two(input: &str) -> impl Display {
let mut safe_sum = 0;
for line in input.lines() {
let report = line
.split_whitespace()
.map(|num: &str| num.parse().unwrap())
.collect();
if is_safe_with_dampener(&report) {
safe_sum += 1;
}
}
safe_sum
}
fn get_day_num() -> u8 {
return 2;
}
}
fn is_safe(report: &Vec<i32>) -> bool {
if report.len() < 2 {
return true;
}
let descending = report[1] < report[0];
for window in report.windows(2) {
if !levels_safe(window[0], window[1], descending) {
return false;
}
}
true
}
fn is_safe_with_dampener(report: &Vec<i32>) -> bool {
if is_safe(report) {
return true;
}
for index in 0..report.len() {
let mut new_report = report.clone();
new_report.remove(index);
if is_safe(&new_report) {
return true;
}
}
false
}
fn levels_safe(previous_level: i32, current_level: i32, descending: bool) -> bool {
let distance = (current_level - previous_level).abs();
(current_level < previous_level) == descending && distance <= 3 && distance > 0
}