AoC2021/src/day01.rs

73 lines
1.9 KiB
Rust

use anyhow::Result;
pub struct Day01(Vec<i32>);
impl crate::day::Day for Day01 {
fn init(f: String) -> Result<Self> {
let v = f.lines().map(str::parse).collect::<Result<Vec<_>, _>>()?;
Ok(Self(v))
}
fn part1(&self) -> Result<String> {
let (a, _) = self.0.iter().copied().fold((0, -1), increments);
Ok(format!("{}", a))
}
fn part2(&self) -> Result<String> {
let ws = self.0.windows(3).map(|a| a.iter().fold(0, std::ops::Add::add)).collect::<Vec<i32>>();
let (a, _) = ws.iter().copied().fold((0, -1), increments);
Ok(format!("{}", a))
}
}
fn increments((a, b): (i32, i32), c: i32) -> (i32, i32) {
if b == -1 {
(a, c)
} else if c > b {
(a + 1, c)
} else {
(a, c)
}
}
#[cfg(test)]
pub mod tests {
use std::fs::read_to_string;
use super::Day01;
use crate::day::Day;
#[test]
pub fn part1_real() -> anyhow::Result<()> {
let f = read_to_string("./input/day01")?;
let d = Day01::init(f)?;
assert_eq!("1466", d.part1()?);
Ok(())
}
#[test]
pub fn part2_real() -> anyhow::Result<()> {
let f = read_to_string("./input/day01")?;
let d = Day01::init(f)?;
assert_eq!("1491", d.part2()?);
Ok(())
}
#[test]
pub fn part1_test() -> anyhow::Result<()>{
let v = vec![199, 200, 208, 210, 200, 207, 240, 269, 260, 263];
let strs = v.iter().map(i32::to_string).collect::<Vec<String>>().join("\n");
let d = Day01::init(strs)?;
assert_eq!("7", d.part1()?);
Ok(())
}
#[test]
pub fn part2_test() -> anyhow::Result<()>{
let v = vec![199, 200, 208, 210, 200, 207, 240, 269, 260, 263];
let strs = v.iter().map(i32::to_string).collect::<Vec<String>>().join("\n");
let d = Day01::init(strs)?;
assert_eq!("5", d.part2()?);
Ok(())
}
}