diff options
Diffstat (limited to '2022/src/day04.rs')
-rw-r--r-- | 2022/src/day04.rs | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/2022/src/day04.rs b/2022/src/day04.rs new file mode 100644 index 0000000..052dde1 --- /dev/null +++ b/2022/src/day04.rs @@ -0,0 +1,35 @@ +mod utils; + +use std::ops::RangeInclusive; + +use utils::{iter_pair, read_input}; + +fn main() { + let input = read_input(); + + let pairs = input.lines().map(|x| { + iter_pair(x.split(',').map(|x| -> RangeInclusive<usize> { + let (start, end) = iter_pair(x.split('-')); + start.parse().unwrap()..=end.parse().unwrap() + })) + }); + + let (fully_contains, partially_contains) = pairs + .map(|(a, b)| (fully_overlap(&a, &b), partially_overlap(&a, &b))) + .fold((0, 0), |(acc_full, acc_part), (full, part)| { + (acc_full + full as usize, acc_part + part as usize) + }); + + println!("Part 1: {}", fully_contains); + println!("Part 2: {}", partially_contains); +} + +#[inline(always)] +fn fully_overlap<T: PartialOrd>(a: &RangeInclusive<T>, b: &RangeInclusive<T>) -> bool { + (a.contains(b.start()) && a.contains(b.end())) || (b.contains(a.start()) && b.contains(a.end())) +} + +#[inline(always)] +fn partially_overlap<T: PartialOrd>(a: &RangeInclusive<T>, b: &RangeInclusive<T>) -> bool { + a.contains(b.start()) || a.contains(b.end()) || b.contains(a.start()) || b.contains(a.end()) +} |