generated from fspoettel/advent-of-code-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path02.rs
103 lines (85 loc) · 2.52 KB
/
02.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
advent_of_code::solution!(2);
pub fn part_one(input: &str) -> Option<u32> {
let mut safe_count = 0;
// let mut unsafe_count = 0;
// input.lines().map(|line| {
// let numbers = line.split_whitespace().map(|item| {
// item.parse::<u32>().unwrap()
// }).collect();
// if checking_level(numbers) {
// safe_count += 1
// }
// }).sum();
for line in input.lines() {
// println!("{}", line);
let numbers: Vec<i32> = line
.split_whitespace()
.filter_map(|item| item.parse::<i32>().ok())
.collect();
if checking_level(&numbers) {
safe_count += 1;
}
}
// println!("{}",safe_count);
Some(safe_count as u32)
}
fn checking_level(numbers: &[i32]) -> bool {
let mut is_increasing = true;
let mut is_decreasing = true;
for i in 0..numbers.len() - 1 {
// let diff = (&numbers - &numbers).abs();
let curr = numbers[i];
let next = numbers[i + 1];
let diff = (next - curr).abs();
if !(1..=3).contains(&diff) {
//unsafe
return false;
}
match curr < next {
true => is_decreasing = false,
false => is_increasing = false,
}
}
is_increasing || is_decreasing
}
pub fn part_two(input: &str) -> Option<u32> {
let mut safe_count = 0;
// let mut unsafe_count = 0;
for line in input.lines() {
// println!("{}", line);
let numbers: Vec<i32> = line
.split_whitespace()
.map(|item| item.parse::<i32>().unwrap())
.collect();
if checking_level(&numbers) {
safe_count += 1;
} else {
// try to remove item and check again
for i in 0..numbers.len() {
let mut cleaned_level = numbers.to_vec();
cleaned_level.remove(i);
if checking_level(&cleaned_level) {
safe_count += 1;
break;
}
}
// unsafe_count += 1;
}
}
// println!("{}",safe_count);
Some(safe_count 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));
}
}