Skip to content

Commit ad81b0a

Browse files
Solve Day 2 Part 2
1 parent 41754a0 commit ad81b0a

File tree

1 file changed

+27
-2
lines changed

1 file changed

+27
-2
lines changed

src/bin/02.rs

+27-2
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,32 @@ pub fn part_one(input: &str) -> Option<u32> {
2424
}
2525

2626
pub fn part_two(input: &str) -> Option<u32> {
27-
None
27+
let reports: Vec<Vec<i32>> = input
28+
.lines()
29+
.filter_map(|line| {
30+
Some(
31+
line.split_whitespace()
32+
.filter_map(|x| x.parse::<i32>().ok())
33+
.collect::<Vec<i32>>(),
34+
)
35+
})
36+
.collect();
37+
38+
let is_valid = |report: &[i32]| {
39+
report.windows(2).all(|w| (1..=3).contains(&(w[1] - w[0])))
40+
|| report.windows(2).all(|w| (1..=3).contains(&(w[0] - w[1])))
41+
};
42+
43+
let num_safe: u32 = reports
44+
.iter()
45+
.filter(|report| {
46+
(0..report.len()).any(|i| {
47+
is_valid(&report[..i].iter().chain(&report[i+1..]).copied().collect::<Vec<i32>>())
48+
})
49+
})
50+
.count() as u32;
51+
52+
Some(num_safe)
2853
}
2954

3055
#[cfg(test)]
@@ -40,6 +65,6 @@ mod tests {
4065
#[test]
4166
fn test_part_two() {
4267
let result = part_two(&advent_of_code::template::read_file("examples", DAY));
43-
assert_eq!(result, None);
68+
assert_eq!(result, Some(4));
4469
}
4570
}

0 commit comments

Comments
 (0)