From 7da0e7bfac7add57cd7a57a77a94985fdda4d532 Mon Sep 17 00:00:00 2001 From: Daniel Seiller Date: Sun, 4 Dec 2022 15:11:46 +0100 Subject: [PATCH] Day 04 --- src/day04.rs | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 1 + 2 files changed, 58 insertions(+) create mode 100644 src/day04.rs diff --git a/src/day04.rs b/src/day04.rs new file mode 100644 index 0000000..dd7b202 --- /dev/null +++ b/src/day04.rs @@ -0,0 +1,57 @@ +use aoc_runner_derive::{aoc, aoc_generator}; +#[derive(Debug)] +pub struct Range(u8,u8); + +impl Range { + fn contains(&self, other: &Self) -> bool { + self.0 <= other.0 && self.1 >= other.1 + } + fn overlaps(&self, other: &Self) -> bool { + (self.0 <= other.0 && other.0 <= self.1) || (self.0 <= other.1 && other.1 <= self.1) + } +} + +fn parse_range(range: &str) -> Range { + let mut range = range.split('-').map(|v| v.parse().unwrap()); + let start = range.next().unwrap(); + let end = range.next().unwrap(); + Range(start, end) +} + +fn parse_line(line: &str) -> (Range, Range) { + let mut line = line.split(','); + let first = line.next().unwrap(); + let second = line.next().unwrap(); + (parse_range(first), parse_range(second)) +} + +#[aoc_generator(day4)] +pub fn input_generator(input: &str) -> Vec<(Range, Range)> { + let mut ret = vec![]; + for line in input.lines() { + ret.push(parse_line(line)) + } + ret +} + +#[aoc(day4, part1)] +pub fn solve_part1(input: &[(Range, Range)]) -> usize { + let mut count = 0; + for (a, b) in input { + if a.contains(b) || b.contains(a) { + count += 1; + } + } + count +} + +#[aoc(day4, part2)] +pub fn solve_part2(input: &[(Range, Range)]) -> usize { + let mut count = 0; + for (a, b) in input { + if a.overlaps(b) || b.overlaps(a) { + count += 1; + } + } + count +} diff --git a/src/lib.rs b/src/lib.rs index 6d55771..dfac4ac 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,4 +2,5 @@ use aoc_runner_derive::aoc_lib; pub mod day01; pub mod day02; pub mod day03; +pub mod day04; aoc_lib! { year = 2022 }