generated from fspoettel/advent-of-code-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
04.rs
64 lines (51 loc) · 1.55 KB
/
04.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
advent_of_code::solution!(4);
use regex::Regex;
use std::collections::BTreeSet;
use std::ops::RangeInclusive;
use advent_of_code::majcn::parse::ParseRegex;
fn parse_data(input: &str) -> Vec<(RangeInclusive<u32>, RangeInclusive<u32>)> {
let re = Regex::new(r"^(\d+)-(\d+),(\d+)-(\d+)$").unwrap();
input
.lines()
.map(|x| re.parse_u32(x))
.map(|[r1_min, r1_max, r2_min, r2_max]| (r1_min..=r1_max, r2_min..=r2_max))
.collect()
}
pub fn part_one(input: &str) -> Option<u32> {
let data = parse_data(input);
let result = data
.into_iter()
.map(|(r1, r2)| (r1.collect::<BTreeSet<u32>>(), r2.collect::<BTreeSet<u32>>()))
.filter(|(s1, s2)| {
if s1.len() > s2.len() {
s2.is_subset(s1)
} else {
s1.is_subset(s2)
}
})
.count() as u32;
Some(result)
}
pub fn part_two(input: &str) -> Option<u32> {
let data = parse_data(input);
let result = data
.into_iter()
.map(|(r1, r2)| (r1.collect::<BTreeSet<u32>>(), r2.collect::<BTreeSet<u32>>()))
.filter(|(s1, s2)| !s1.is_disjoint(s2))
.count() as u32;
Some(result)
}
#[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));
}
}