Day 04
This commit is contained in:
parent
4aaf8aca52
commit
7da0e7bfac
2 changed files with 58 additions and 0 deletions
57
src/day04.rs
Normal file
57
src/day04.rs
Normal file
|
@ -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
|
||||
}
|
|
@ -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 }
|
||||
|
|
Loading…
Reference in a new issue