Implement 2022 day 4

This commit is contained in:
2022-12-04 11:14:23 +01:00
parent e1b3b9d179
commit 9d23e80256
5 changed files with 1103 additions and 5 deletions

View File

@@ -8,7 +8,7 @@ use criterion::BenchmarkId;
use criterion::Criterion;
/// Number of days we have an implementation to benchmark
const DAYS_IMPLEMENTED: u8 = 3;
const DAYS_IMPLEMENTED: u8 = 4;
fn read_input(day: u8) -> Vec<u8> {
let input_path = format!("inputs/{:02}.txt", day);

1000
2022/inputs/04.txt Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -92,3 +92,15 @@ where
}
}
}
/// Return the minimum and maximum of two unordered variables
pub fn minmax<T>(a: T, b: T) -> (T, T)
where
T: PartialOrd,
{
if a < b {
(a, b)
} else {
(b, a)
}
}

View File

@@ -1,9 +1,89 @@
use anyhow::Result;
use nom::bytes::complete::tag;
use nom::character::complete::newline;
use nom::combinator::map;
use nom::multi::many0;
use nom::sequence::separated_pair;
use nom::sequence::terminated;
use nom::IResult;
pub fn part1(_input: &[u8]) -> Result<String> {
todo!()
use crate::common::minmax;
use crate::common::parse_input;
#[derive(Copy, Clone, PartialOrd, PartialEq)]
struct Assignment(u32, u32);
impl Assignment {
fn one_contains(self, other: Self) -> bool {
let (first, second) = minmax(self, other);
if second.0 == first.0 {
first.1 <= second.1
} else {
second.0 <= first.1 && second.1 <= first.1
}
}
fn one_overlaps(self, other: Self) -> bool {
let (first, second) = minmax(self, other);
if second.0 == first.0 {
first.1 <= second.1
} else {
second.0 <= first.1
}
}
}
pub fn part2(_input: &[u8]) -> Result<String> {
todo!()
fn parse_assignments(input: &[u8]) -> IResult<&[u8], Vec<(Assignment, Assignment)>> {
use nom::character::complete::u32;
fn parse_single(input: &[u8]) -> IResult<&[u8], Assignment> {
map(separated_pair(u32, tag("-"), u32), |(start, end)| {
Assignment(start, end)
})(input)
}
let parse_line = separated_pair(parse_single, tag(","), parse_single);
many0(terminated(parse_line, newline))(input)
}
pub fn part1(input: &[u8]) -> Result<String> {
let assigments = parse_input(input, parse_assignments)?;
let overlapping = assigments
.into_iter()
.filter(|&(a, b)| a.one_contains(b))
.count();
Ok(overlapping.to_string())
}
pub fn part2(input: &[u8]) -> Result<String> {
let assigments = parse_input(input, parse_assignments)?;
let overlapping = assigments
.into_iter()
.filter(|&(a, b)| a.one_overlaps(b))
.count();
Ok(overlapping.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
const SAMPLE: &[u8] = include_bytes!("samples/04.txt");
#[test]
fn sample_part1() {
assert_eq!(part1(SAMPLE).unwrap(), "2")
}
#[test]
fn sample_part2() {
assert_eq!(part2(SAMPLE).unwrap(), "4")
}
}

6
2022/src/samples/04.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