aoc2022/src/day04.rs
2022-12-04 12:07:29 -06:00

46 lines
1.3 KiB
Rust

use std::ops::RangeInclusive;
use aoc_runner_derive::{aoc, aoc_generator};
fn parse_range(range: &str) -> RangeInclusive<u64> {
let (start, end) = range.split_once('-').unwrap();
start.parse().unwrap()..=end.parse().unwrap()
}
#[aoc_generator(day4)]
pub fn input_generator(input: &str) -> Vec<(RangeInclusive<u64>, RangeInclusive<u64>)> {
input
.lines()
.map(|l| {
let (first, second) = l.split_once(',').unwrap();
(parse_range(first), parse_range(second))
})
.collect()
}
fn contains_range(slf: &RangeInclusive<u64>, other: &RangeInclusive<u64>) -> bool {
slf.start() <= other.start() && slf.end() >= other.end()
}
fn overlaps_with_range(slf: &RangeInclusive<u64>, other: &RangeInclusive<u64>) -> bool {
slf.contains(other.start()) || slf.contains(other.end())
}
#[aoc(day4, part1)]
pub fn solve_part1(input: &[(RangeInclusive<u64>, RangeInclusive<u64>)]) -> usize {
input
.iter()
.filter(|(first, second)| contains_range(first, second) | contains_range(second, first))
.count()
}
#[aoc(day4, part2)]
pub fn solve_part2(input: &[(RangeInclusive<u64>, RangeInclusive<u64>)]) -> usize {
input
.iter()
.filter(|(first, second)| {
overlaps_with_range(first, second) | overlaps_with_range(second, first)
})
.count()
}