AoC2021/src/day1.rs

71 lines
1.8 KiB
Rust

use std::fs::read_to_string;
#[derive(Eq, PartialEq, Ord, PartialOrd, Clone)]
pub struct Day1(Vec<i32>);
impl crate::day::Day for Day1 {
fn init(f: String) -> Self {
let v = f.split('\n').map(|x| x.parse::<i32>().unwrap()).collect::<Vec<i32>>();
Self(v)
}
fn part1(&self) -> String {
let (a, _) = self.0.iter().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().fold((0, -1), increments);
format!("{}", a)
}
}
fn increments((a, b): (i32, i32), c: &i32) -> (i32, i32) {
let c = *c;
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::Day1;
use crate::day::Day;
#[test]
pub fn part1_real() {
let f = read_to_string("./input/day1").expect("Could not load input");
let d = Day1::init(f);
assert_eq!("1466", d.part1())
}
#[test]
pub fn part2_real() {
let f = read_to_string("./input/day1").expect("Could not load input");
let d = Day1::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 = Day1::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 = Day1::init(strs);
assert_eq!("5", d.part2())
}
}