Created
December 4, 2022 16:09
-
-
Save saolsen/94fd9a2db09f1293e1eec394e8392a33 to your computer and use it in GitHub Desktop.
aoc 2022 day04
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn parse_line(line: &str) -> (i32, i32, i32, i32) { | |
let mut split = line.split(","); | |
let left = split.next().unwrap(); | |
let mut ls = left.split("-"); | |
let left_from: i32 = ls.next().unwrap().parse().unwrap(); | |
let left_to: i32 = ls.next().unwrap().parse().unwrap(); | |
let right = split.next().unwrap(); | |
let mut rs = right.split("-"); | |
let right_from: i32 = rs.next().unwrap().parse().unwrap(); | |
let right_to: i32 = rs.next().unwrap().parse().unwrap(); | |
(left_from, left_to, right_from, right_to) | |
} | |
// check if left fully contains right | |
fn fully_contains(left_from: i32, left_to: i32, right_from: i32, right_to: i32) -> bool { | |
left_from <= right_from && left_to >= right_to | |
} | |
fn overlap_at_all(left_from: i32, left_to: i32, right_from: i32, right_to: i32) -> bool { | |
// there are only 2 cases where they don't overlap | |
// one whole interval is less than the start of the other | |
!((left_from < right_from && left_to < right_from) | |
|| (right_from < left_from && right_to < left_from)) | |
} | |
fn main() { | |
let input = include_str!("day04_input.txt"); | |
let mut num_fully_contained = 0; | |
let mut num_overlap = 0; | |
for line in input.split("\n") { | |
let (left_from, left_to, right_from, right_to) = parse_line(line); | |
if fully_contains(left_from, left_to, right_from, right_to) | |
|| fully_contains(right_from, right_to, left_from, left_to) | |
{ | |
num_fully_contained += 1; | |
} | |
if overlap_at_all(left_from, left_to, right_from, right_to) { | |
num_overlap += 1; | |
} | |
} | |
println!("num fully contained {num_fully_contained}"); | |
println!("num overlap {num_overlap}"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment