AoC2021/src/day01.rs
Julius 183db991f9
All checks were successful
continuous-integration/drone/push Build is passing
Day 3 and cleanup
2021-12-03 10:02:46 +01:00

68 lines
1.7 KiB
Rust

pub struct Day01(Vec<i32>);
impl crate::day::Day for Day01 {
fn init(f: String) -> Self {
let v = f.lines().map(|x| x.parse::<i32>().unwrap()).collect::<Vec<i32>>();
Self(v)
}
fn part1(&self) -> String {
let (a, _) = self.0.iter().copied().fold((0, -1), increments);
format!("{}", a)
}
fn part2(&self) -> 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);
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() {
let f = read_to_string("./input/day01").expect("Could not load input");
let d = Day01::init(f);
assert_eq!("1466", d.part1())
}
#[test]
pub fn part2_real() {
let f = read_to_string("./input/day01").expect("Could not load input");
let d = Day01::init(f);
assert_eq!("1491", d.part2())
}
#[test]
pub fn part1_test() {
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())
}
#[test]
pub fn part2_test() {
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())
}
}