1
0
Fork 0

Solve day 4

This commit is contained in:
Lars Martens 2022-12-04 13:13:38 +01:00
parent 5c23f8a99a
commit 5c01353113
Signed by: haselkern
GPG key ID: B5CF1F363C179AD4
3 changed files with 1069 additions and 0 deletions

1000
input/04 Normal file

File diff suppressed because it is too large Load diff

6
input/04-test Normal file
View file

@ -0,0 +1,6 @@
2-4,6-8
2-3,4-5
5-7,7-9
2-8,3-7
6-6,4-6
2-6,4-8

63
src/bin/04.rs Normal file
View file

@ -0,0 +1,63 @@
use aoc2022::*;
const INPUT: &str = include_str!("../../input/04");
fn main() {
let solution = INPUT
.lines()
.map(parse_line)
.filter(|&(a, b)| a.contains(b) || b.contains(a))
.count();
solved_level_1(solution);
let solution = INPUT
.lines()
.map(parse_line)
.filter(|&(a, b)| a.overlaps(b))
.count();
solved_level_2(solution);
}
fn parse_line(line: &str) -> (Range, Range) {
let (a, b) = line.split_once(',').unwrap();
(a.into(), b.into())
}
#[derive(Clone, Copy)]
struct Range {
start: i64,
end: i64,
}
impl Range {
fn contains<O>(self, other: O) -> bool
where
O: Into<Self>,
{
let other = other.into();
other.start >= self.start && other.end <= self.end
}
fn overlaps(self, other: Self) -> bool {
self.contains(other.start)
|| self.contains(other.end)
|| other.contains(self.start)
|| other.contains(self.end)
}
}
impl From<&str> for Range {
fn from(s: &str) -> Self {
let (start, end) = s.split_once('-').unwrap();
Self {
start: start.parse().unwrap(),
end: end.parse().unwrap(),
}
}
}
impl From<i64> for Range {
fn from(n: i64) -> Self {
Self { start: n, end: n }
}
}