AoC2021/src/day01.rs

59 lines
1.5 KiB
Rust
Raw Permalink Normal View History

2021-12-07 19:40:41 +01:00
use anyhow::Result;
2021-12-02 14:44:38 +01:00
2021-12-01 20:53:49 +01:00
pub struct Day01(Vec<i32>);
2021-12-01 17:07:17 +01:00
2021-12-01 20:53:49 +01:00
impl crate::day::Day for Day01 {
2021-12-07 19:40:41 +01:00
fn init(f: String) -> Result<Self> {
let v = f.lines().map(str::parse).collect::<Result<Vec<_>, _>>()?;
Ok(Self(v))
2021-12-01 17:07:17 +01:00
}
2021-12-07 19:40:41 +01:00
fn part1(&self) -> Result<String> {
2021-12-03 10:02:46 +01:00
let (a, _) = self.0.iter().copied().fold((0, -1), increments);
2021-12-07 19:40:41 +01:00
Ok(format!("{}", a))
2021-12-01 17:07:17 +01:00
}
2021-12-07 19:40:41 +01:00
fn part2(&self) -> Result<String> {
2021-12-01 17:07:17 +01:00
let ws = self.0.windows(3).map(|a| a.iter().fold(0, std::ops::Add::add)).collect::<Vec<i32>>();
2021-12-03 10:02:46 +01:00
let (a, _) = ws.iter().copied().fold((0, -1), increments);
2021-12-07 19:40:41 +01:00
Ok(format!("{}", a))
2021-12-01 17:07:17 +01:00
}
}
2021-12-03 10:02:46 +01:00
fn increments((a, b): (i32, i32), c: i32) -> (i32, i32) {
2021-12-01 17:07:17 +01:00
if b == -1 {
(a, c)
} else if c > b {
(a + 1, c)
} else {
(a, c)
}
}
#[cfg(test)]
pub mod tests {
2021-12-01 20:53:49 +01:00
use super::Day01;
2021-12-01 17:07:17 +01:00
use crate::day::Day;
2021-12-16 20:23:05 +01:00
use crate::day_tests;
2021-12-01 17:07:17 +01:00
2021-12-16 20:23:05 +01:00
day_tests!(Day01, "01", "1466", "1491");
2021-12-01 17:07:17 +01:00
#[test]
2021-12-07 19:40:41 +01:00
pub fn part1_test() -> anyhow::Result<()>{
2021-12-01 17:07:17 +01:00
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");
2021-12-07 19:40:41 +01:00
let d = Day01::init(strs)?;
assert_eq!("7", d.part1()?);
Ok(())
2021-12-01 17:07:17 +01:00
}
#[test]
2021-12-07 19:40:41 +01:00
pub fn part2_test() -> anyhow::Result<()>{
2021-12-01 17:07:17 +01:00
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");
2021-12-07 19:40:41 +01:00
let d = Day01::init(strs)?;
assert_eq!("5", d.part2()?);
Ok(())
2021-12-01 17:07:17 +01:00
}
}