Skip to content

Commit a141de6

Browse files
committed
Day 2
1 parent b10b966 commit a141de6

File tree

2 files changed

+76
-0
lines changed

2 files changed

+76
-0
lines changed

data/examples/02.txt

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
7 6 4 2 1
2+
1 2 7 8 9
3+
9 7 6 2 1
4+
1 3 2 4 5
5+
8 6 4 4 1
6+
1 3 6 7 9

src/bin/02.rs

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
advent_of_code::solution!(2);
2+
3+
fn is_safe(data: &Vec<u32>) -> bool {
4+
let mut previous_direction = None;
5+
for i in 0..(data.len() - 1) {
6+
let diff = data[i].abs_diff(data[i + 1]);
7+
if diff > 3 {
8+
return false;
9+
}
10+
let direction = data[i].cmp(&data[i + 1]);
11+
match previous_direction {
12+
Some(previous_direction) => if previous_direction != direction {
13+
return false;
14+
},
15+
None => previous_direction = Some(direction)
16+
}
17+
}
18+
true
19+
}
20+
21+
fn is_safe_lenient(data: &Vec<u32>) -> bool {
22+
if is_safe(data) {
23+
return true;
24+
}
25+
for i in 0..data.len() {
26+
let mut modified_data = data.clone();
27+
modified_data.remove(i);
28+
if is_safe(&modified_data) {
29+
return true
30+
}
31+
}
32+
false
33+
}
34+
35+
fn count_safe_reports<P>(input: &str, predicate: P) -> u32
36+
where
37+
P: FnMut(&Vec<u32>) -> bool
38+
{
39+
input.lines()
40+
.map(|line| line.split_whitespace()
41+
.map(|number| number.parse::<u32>().unwrap())
42+
.collect::<Vec<u32>>())
43+
.filter(predicate)
44+
.count() as u32
45+
}
46+
47+
pub fn part_one(input: &str) -> Option<u32> {
48+
Some(count_safe_reports(input, is_safe))
49+
}
50+
51+
pub fn part_two(input: &str) -> Option<u32> {
52+
Some(count_safe_reports(input, is_safe_lenient))
53+
}
54+
55+
#[cfg(test)]
56+
mod tests {
57+
use super::*;
58+
59+
#[test]
60+
fn test_part_one() {
61+
let result = part_one(&advent_of_code::template::read_file("examples", DAY));
62+
assert_eq!(result, Some(2));
63+
}
64+
65+
#[test]
66+
fn test_part_two() {
67+
let result = part_two(&advent_of_code::template::read_file("examples", DAY));
68+
assert_eq!(result, Some(4));
69+
}
70+
}

0 commit comments

Comments
 (0)