diff --git a/src/day04.rs b/src/day04.rs new file mode 100644 index 0000000..4f66845 --- /dev/null +++ b/src/day04.rs @@ -0,0 +1,45 @@ +use std::ops::RangeInclusive; + +use aoc_runner_derive::{aoc, aoc_generator}; + +fn parse_range(range: &str) -> RangeInclusive { + let (start, end) = range.split_once('-').unwrap(); + start.parse().unwrap()..=end.parse().unwrap() +} + +#[aoc_generator(day4)] +pub fn input_generator(input: &str) -> Vec<(RangeInclusive, RangeInclusive)> { + input + .lines() + .map(|l| { + let (first, second) = l.split_once(',').unwrap(); + (parse_range(first), parse_range(second)) + }) + .collect() +} + +fn contains_range(slf: &RangeInclusive, other: &RangeInclusive) -> bool { + slf.start() <= other.start() && slf.end() >= other.end() +} + +fn overlaps_with_range(slf: &RangeInclusive, other: &RangeInclusive) -> bool { + slf.contains(other.start()) +} + +#[aoc(day4, part1)] +pub fn solve_part1(input: &[(RangeInclusive, RangeInclusive)]) -> usize { + input + .iter() + .filter(|(first, second)| contains_range(first, second) | contains_range(second, first)) + .count() +} + +#[aoc(day4, part2)] +pub fn solve_part2(input: &[(RangeInclusive, RangeInclusive)]) -> usize { + input + .iter() + .filter(|(first, second)| { + overlaps_with_range(first, second) | overlaps_with_range(second, first) + }) + .count() +} diff --git a/src/lib.rs b/src/lib.rs index 5616faa..010163f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -3,5 +3,6 @@ use aoc_runner_derive::aoc_lib; pub mod day01; pub mod day02; pub mod day03; +pub mod day04; aoc_lib! { year = 2022 }