-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday02.rs
87 lines (73 loc) · 2.15 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
83
84
85
86
87
use std::fs;
pub fn day02(print: fn(usize)) {
print(part_a(fs::read_to_string("input/2024/day02/input.txt").unwrap()));
print(part_b(fs::read_to_string("input/2024/day02/input.txt").unwrap()));
}
fn part_a(input: String) -> usize {
input
.lines()
.filter(|line| {
let nums: Vec<u32> = line
.split(" ")
.map(|num| num.parse::<u32>().unwrap())
.collect();
is_correct(nums)
})
.count()
}
fn part_b(input: String) -> usize {
input
.lines()
.filter(|line| {
let nums: Vec<u32> = line
.split(" ")
.map(|num| num.parse::<u32>().unwrap())
.collect();
if is_correct(nums.clone()) {
return true;
}
for i in 0..nums.len() {
let new_nums = nums[..i].iter().chain(nums[(i + 1)..].iter())
.cloned().collect();
if is_correct(new_nums) {
return true;
}
}
return false;
})
.count()
}
fn is_correct(nums: Vec<u32>) -> bool {
let mut diff = true;
let mut increases = true;
let mut decreases = true;
for i in 0..nums.len() - 1 {
let a = nums[i];
let b = nums[i + 1];
if a < b && decreases {
decreases = false;
}
if a > b && increases {
increases = false;
}
if a.max(b) - a.min(b) > 3 || a.max(b) - a.min(b) < 1 {
diff = false;
}
}
diff && (increases || decreases)
}
#[cfg(test)]
mod day02_tests {
use std::fs;
use crate::y2024::day02::{part_a, part_b};
#[test]
fn test_works() {
assert_eq!(2, part_a(fs::read_to_string("input/2024/day02/test.txt").unwrap()));
assert_eq!(4, part_b(fs::read_to_string("input/2024/day02/test.txt").unwrap()));
}
#[test]
fn input_works() {
assert_eq!(269, part_a(fs::read_to_string("input/2024/day02/input.txt").unwrap()));
assert_eq!(337, part_b(fs::read_to_string("input/2024/day02/input.txt").unwrap()));
}
}