Made everything a bit more rustic

This commit is contained in:
Rüdiger Ludwig 2023-07-29 17:02:25 +02:00
parent 7f5b6e03f9
commit a5f19ecae1
22 changed files with 376 additions and 274 deletions

View file

@ -1,3 +1,5 @@
use crate::common::file::split_lines;
use super::template::{DayTrait, ResultType};
use itertools::{iproduct, FoldWhile, Itertools};
use thiserror::Error;
@ -11,14 +13,14 @@ impl DayTrait for Day {
DAY_NUMBER
}
fn part1(&self, lines: &[String]) -> anyhow::Result<ResultType> {
let forest = Forest::parse(lines)?;
fn part1(&self, lines: &str) -> anyhow::Result<ResultType> {
let forest = Forest::try_from(lines)?;
let result = forest.count_visible();
Ok(ResultType::Integer(result))
}
fn part2(&self, lines: &[String]) -> anyhow::Result<ResultType> {
let forest = Forest::parse(lines)?;
fn part2(&self, lines: &str) -> anyhow::Result<ResultType> {
let forest = Forest::try_from(lines)?;
let result = forest.best_score();
Ok(ResultType::Integer(result))
}
@ -67,18 +69,6 @@ impl Forest {
})
}
pub fn parse(lines: &[String]) -> Result<Forest, ForestError> {
lines
.iter()
.map(|line| {
line.chars()
.map(|height| height.to_digit(10).ok_or(ForestError::NoLegalDigit(height)))
.collect::<Result<Vec<_>, _>>()
})
.collect::<Result<Vec<_>, _>>()
.and_then(Forest::create)
}
pub fn count_visible(&self) -> i64 {
let mut vis_count = 2 * (self.width + self.height - 2) as i64;
let mut visible = vec![vec![false; self.width - 2]; self.height - 2];
@ -191,17 +181,32 @@ impl Forest {
}
}
impl TryFrom<&str> for Forest {
type Error = ForestError;
fn try_from(lines: &str) -> Result<Self, Self::Error> {
split_lines(lines)
.map(|line| {
line.chars()
.map(|height| height.to_digit(10).ok_or(ForestError::NoLegalDigit(height)))
.collect::<Result<Vec<_>, _>>()
})
.collect::<Result<Vec<_>, _>>()
.and_then(Forest::create)
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::common::file::read_lines;
use crate::common::file::read_string;
use anyhow::Result;
#[test]
fn test_parse() -> Result<()> {
let day = Day {};
let lines = read_lines(day.get_day_number(), "example01.txt")?;
let forest = Forest::parse(&lines)?;
let lines = read_string(day.get_day_number(), "example01.txt")?;
let forest = Forest::try_from(lines.as_str())?;
assert_eq!(forest.width, 5);
assert_eq!(forest.height, 5);
@ -211,7 +216,7 @@ mod test {
#[test]
fn test_part1() -> Result<()> {
let day = Day {};
let lines = read_lines(day.get_day_number(), "example01.txt")?;
let lines = read_string(day.get_day_number(), "example01.txt")?;
let expected = ResultType::Integer(21);
let result = day.part1(&lines)?;
assert_eq!(result, expected);
@ -222,7 +227,7 @@ mod test {
#[test]
fn test_part2() -> Result<()> {
let day = Day {};
let lines = read_lines(day.get_day_number(), "example01.txt")?;
let lines = read_string(day.get_day_number(), "example01.txt")?;
let expected = ResultType::Integer(8);
let result = day.part2(&lines)?;
assert_eq!(result, expected);