diff --git a/d4/Cargo.lock b/d4/Cargo.lock new file mode 100644 index 0000000..35783ca --- /dev/null +++ b/d4/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "d4" +version = "0.1.0" diff --git a/d4/Cargo.toml b/d4/Cargo.toml new file mode 100644 index 0000000..d057ef5 --- /dev/null +++ b/d4/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "d4" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/d4/src/main.rs b/d4/src/main.rs new file mode 100644 index 0000000..e4259e9 --- /dev/null +++ b/d4/src/main.rs @@ -0,0 +1,59 @@ +use std::{fs::read_to_string, io::Result}; + +#[derive(Debug, PartialEq, Eq, Clone, Copy)] +struct Range { + start: u32, + end: u32, +} + +impl Range { + pub fn from_str(s: &str) -> Self { + let mut parts = s.split("-"); + let start = parts.next().unwrap().parse().unwrap(); + let end = parts.next().unwrap().parse().unwrap(); + Self { start, end } + } + + pub fn includes(self, other: Self) -> bool { + self.start <= other.start && self.end >= other.end + } + + pub fn overlaps(self, other: Self) -> bool { + (self.start <= other.start && other.start <= self.end) + || (other.start <= self.start && self.start <= other.end) + || (self.end <= other.end && other.end <= self.end) + || (other.end <= self.end && self.end <= other.end) + } +} + +fn main() -> Result<()> { + let mut result_p1 = 0; + let mut result_p2 = 0; + + for line in read_to_string("input.txt")?.split("\n") { + if line.is_empty() { + continue; + } + + let (left, right) = { + let mut parts = line.split(","); + let left = parts.next(); + (left.unwrap(), parts.next().unwrap()) + }; + + let left = Range::from_str(left); + let right = Range::from_str(right); + + if left.includes(right) || right.includes(left) { + result_p1 += 1; + } + if left.overlaps(right) { + result_p2 += 1; + } + } + + println!("Part 1: {}", result_p1); + println!("Part 2: {}", result_p2); + + Ok(()) +}