parent
40922a13cb
commit
793b6f4033
@ -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" |
@ -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] |
@ -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(()) |
||||
} |
Loading…
Reference in new issue