adventofcode2022/day04/common.rs

75 lines
2.5 KiB
Rust
Raw Normal View History

2022-12-04 15:09:10 +01:00
// Copyright 2022 Christian Ulrich
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
use std::io;
use std::ops::RangeInclusive;
pub struct Assignments {}
#[derive(Debug)]
pub struct Assignment {
range1: RangeInclusive<u8>,
range2: RangeInclusive<u8>,
}
impl Iterator for Assignments {
type Item = Result<Assignment, &'static str>;
fn next(&mut self) -> Option<Self::Item> {
if let Some(line) = io::stdin().lines().next() {
let line = line.unwrap();
if line.len() > 0 {
if let Some((left, right)) = line.split_once(',') {
if let (Some((s1, e1)), Some((s2, e2))) =
(left.split_once('-'), right.split_once('-'))
{
if let (Ok(s1), Ok(e1), Ok(s2), Ok(e2)) = (
s1.parse::<u8>(),
e1.parse::<u8>(),
s2.parse::<u8>(),
e2.parse::<u8>(),
) {
return Some(Ok(Assignment::new(s1..=e1, s2..=e2)));
}
}
}
return Some(Err("input file contains invalid line"));
}
}
None
}
}
impl Assignment {
pub fn new(range1: RangeInclusive<u8>, range2: RangeInclusive<u8>) -> Self {
Self {
range1: range1,
range2: range2,
}
}
pub fn has_obsolete_range(&self) -> bool {
self.range1.contains(self.range2.start()) && self.range1.contains(self.range2.end())
|| self.range2.contains(self.range1.start()) && self.range2.contains(self.range1.end())
}
2022-12-04 15:24:03 +01:00
pub fn has_overlapping_ranges(&self) -> bool {
self.range1.contains(self.range2.start())
|| self.range1.contains(self.range2.end())
|| self.range2.contains(self.range1.start())
|| self.range2.contains(self.range1.end())
}
2022-12-04 15:09:10 +01:00
}