From 244d3dfa233371db0adcff329283bb1ce9bba9f5 Mon Sep 17 00:00:00 2001 From: Yigit Sever Date: Tue, 6 Dec 2022 14:47:43 +0300 Subject: 2022, day4: done --- 2022/day4/part2/src/main.rs | 49 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 2022/day4/part2/src/main.rs (limited to '2022/day4/part2/src/main.rs') diff --git a/2022/day4/part2/src/main.rs b/2022/day4/part2/src/main.rs new file mode 100644 index 0000000..d7f378a --- /dev/null +++ b/2022/day4/part2/src/main.rs @@ -0,0 +1,49 @@ +use itertools::Itertools; + +#[derive(Debug)] +struct Elf { + start: usize, + end: usize, +} + +#[derive(Debug)] +struct Pair(Elf, Elf); + +impl Elf { + pub fn new(range: &str) -> Self { + if let Some((start, end)) = range.to_string().split("-").collect_tuple() { + let start: usize = start.parse().unwrap(); + let end: usize = end.parse().unwrap(); + Self { start, end } + } else { + panic!("Expected two elements"); + } + } +} + +impl Pair { + pub fn new(line: &str) -> Self { + if let Some((first, second)) = line.to_string().split(",").collect_tuple() { + Pair(Elf::new(first), Elf::new(second)) + } else { + panic!("Expected two elements"); + } + } +} + +impl Pair { + fn overlaps(&self) -> bool { + !(self.0.end < self.1.start || self.1.end < self.0.start) + } +} + +fn main() { + let sum: usize = include_str!("../../input") + .lines() + .map(|l| Pair::new(l)) + .map(|p| p.overlaps()) + .filter(|r| *r) + .count(); + + println!("{}", sum); +} -- cgit v1.2.3-70-g09d2