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/part1/src/main.rs | 50 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 2022/day4/part1/src/main.rs (limited to '2022/day4/part1/src/main.rs') diff --git a/2022/day4/part1/src/main.rs b/2022/day4/part1/src/main.rs new file mode 100644 index 0000000..a4b7e38 --- /dev/null +++ b/2022/day4/part1/src/main.rs @@ -0,0 +1,50 @@ +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 contains(&self) -> bool { + return (self.0.start <= self.1.start && self.0.end >= self.1.end) + || (self.0.start >= self.1.start && self.0.end <= self.1.end); + } +} + +fn main() { + let sum: usize = include_str!("../../example") + .lines() + .map(|l| Pair::new(l)) + .map(|p| p.contains()) + .filter(|r| *r) + .count(); + + println!("{}", sum); +} -- cgit v1.2.3-70-g09d2