aboutsummaryrefslogtreecommitdiff
path: root/2022/src/day04.rs
diff options
context:
space:
mode:
authorAria <me@aria.rip>2023-01-02 21:58:56 +0000
committerAria <me@aria.rip>2023-01-02 21:58:56 +0000
commit5eb58ad076f2cd435b11b140820da224b60b73d5 (patch)
tree2a67939595fbf993ff04f69b9cd3f0aa20827d96 /2022/src/day04.rs
initial commit
Diffstat (limited to '2022/src/day04.rs')
-rw-r--r--2022/src/day04.rs35
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())
+}