day04 finished

This commit is contained in:
Ruediger Ludwig 2023-01-29 15:12:26 +01:00
parent d7c85a75f6
commit 33eb92e9d1
10 changed files with 1184 additions and 55 deletions

View file

@ -1,8 +1,7 @@
use super::template::{DayTrait, ResultType};
use itertools::Itertools;
use thiserror::Error;
use super::template::{DayTrait, ResultType};
const DAY_NUMBER: usize = 3;
pub struct Day;
@ -12,25 +11,25 @@ impl DayTrait for Day {
DAY_NUMBER
}
fn part1(&self, lines: &str) -> anyhow::Result<ResultType> {
fn part1(&self, lines: &[String]) -> anyhow::Result<ResultType> {
let sum = lines
.split('\n')
.map(|rucksack| find_double(rucksack).and_then(priority))
.collect::<Result<Vec<_>, _>>()?
.iter()
.sum();
.map(|line| find_double(&line))
.map_ok(priority)
.flatten_ok()
.fold_ok(0, |a, b| a + b)?;
Ok(ResultType::IntResult(sum))
}
fn part2(&self, lines: &str) -> anyhow::Result<ResultType> {
fn part2(&self, lines: &[String]) -> anyhow::Result<ResultType> {
let sum = lines
.split('\n')
.iter()
.chunks(3)
.into_iter()
.map(|chunk| find_badge(&chunk.collect::<Vec<_>>()).and_then(priority))
.collect::<Result<Vec<_>, _>>()?
.iter()
.sum();
.map(|chunk| find_badge(&chunk.collect::<Vec<_>>()))
.map_ok(priority)
.flatten_ok()
.fold_ok(0, |a, b| a + b)?;
Ok(ResultType::IntResult(sum))
}
}
@ -72,7 +71,7 @@ fn find_double(content: &str) -> Result<char, RucksackError> {
Err(RucksackError::NoDoubleFound)?
}
fn find_badge<'a>(elves: &[&str]) -> Result<char, RucksackError> {
fn find_badge<'a>(elves: &[&String]) -> Result<char, RucksackError> {
if elves.len() < 2 {
return Err(RucksackError::NeedAtLeastTwo);
};
@ -93,7 +92,7 @@ fn find_badge<'a>(elves: &[&str]) -> Result<char, RucksackError> {
#[cfg(test)]
mod test {
use super::*;
use crate::common::file::read_data;
use crate::common::file::read_lines;
use anyhow::Result;
#[test]
@ -109,7 +108,7 @@ mod test {
#[test]
fn test_part1() -> Result<()> {
let day = Day {};
let lines = read_data(day.get_day_number(), "example01.txt")?;
let lines = read_lines(day.get_day_number(), "example01.txt")?;
let expected = ResultType::IntResult(157);
let result = day.part1(&lines)?;
assert_eq!(result, expected);
@ -117,24 +116,10 @@ mod test {
Ok(())
}
#[test]
fn test_find_badge() -> Result<(), RucksackError> {
let input = vec![
"vJrwpWtwJgWrhcsFMMfFFhFp",
"jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL",
"PmmdzqPrVvPwwTWBwg",
];
let expected = 18;
let result = find_badge(&input).and_then(priority)?;
assert_eq!(result, expected);
Ok(())
}
#[test]
fn test_part2() -> Result<()> {
let day = Day {};
let lines = read_data(day.get_day_number(), "example01.txt")?;
let lines = read_lines(day.get_day_number(), "example01.txt")?;
let expected = ResultType::IntResult(70);
let result = day.part2(&lines)?;
assert_eq!(result, expected);