feat: day 4 (12:04.60)

This commit is contained in:
Ashhhleyyy 2022-12-04 12:18:36 +00:00
parent e2a7024ca4
commit 2b66459ebf
Signed by: ash
GPG key ID: 83B789081A0878FB
3 changed files with 1084 additions and 0 deletions

1000
.aoc-cache/4.txt Normal file

File diff suppressed because it is too large Load diff

78
src/bin/day_4.rs Normal file
View file

@ -0,0 +1,78 @@
use std::ops::RangeInclusive;
use aoc_2022::prelude::*;
type Input = Vec<(RangeInclusive<usize>, RangeInclusive<usize>)>;
fn parse_range(s: &str) -> RangeInclusive<usize> {
let (lower, upper) = s.split_once("-").expect("range to have dash");
let (lower, upper) = (lower.parse::<usize>().expect("valid number"), upper.parse::<usize>().expect("valid number"));
lower..=upper
}
fn parse(s: &str) -> Result<Input> {
Ok(s.lines().map(|line| {
let (a, b) = line.split_once(",").expect("comma in line");
(parse_range(a), parse_range(b))
}).collect::<Vec<_>>())
}
#[aoc(day = 4, parse = parse, test_cases = ["day_4.txt"])]
fn day_4(input: Input) -> Result<()> {
// Part 1
let mut fully_contained = 0;
for (a, b) in &input {
let mut overlaps = true;
for v in a.clone() {
if !b.contains(&v) {
overlaps = false;
break;
}
}
if overlaps {
fully_contained += 1;
continue;
}
overlaps = true;
for v in b.clone() {
if !a.contains(&v) {
overlaps = false;
break;
}
}
if overlaps {
fully_contained += 1;
}
}
println!("Part one: {fully_contained} pairs contain themselves!");
// Part 2
let mut overlapping = 0;
for (a, b) in &input {
let mut overlapped = false;
for v in a.clone() {
if b.contains(&v) {
overlapped = true;
break;
}
}
if overlapped {
overlapping += 1;
continue;
}
for v in b.clone() {
if a.contains(&v) {
overlapped = true;
break;
}
}
if overlapped {
overlapping += 1;
}
}
println!("Part two: {overlapping} pairs overlap in any way");
Ok(())
}

6
test_cases/day_4.txt 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