2021-12-01 17:07:17 +01:00
|
|
|
#[derive(Eq, PartialEq, Ord, PartialOrd, Clone)]
|
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-01 17:07:17 +01:00
|
|
|
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;
|
2021-12-01 20:53:49 +01:00
|
|
|
use super::Day01;
|
2021-12-01 17:07:17 +01:00
|
|
|
use crate::day::Day;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
pub fn part1_real() {
|
2021-12-01 20:53:49 +01:00
|
|
|
let f = read_to_string("./input/day01").expect("Could not load input");
|
|
|
|
let d = Day01::init(f);
|
2021-12-01 17:07:17 +01:00
|
|
|
assert_eq!("1466", d.part1())
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
pub fn part2_real() {
|
2021-12-01 20:53:49 +01:00
|
|
|
let f = read_to_string("./input/day01").expect("Could not load input");
|
|
|
|
let d = Day01::init(f);
|
2021-12-01 17:07:17 +01:00
|
|
|
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");
|
2021-12-01 20:53:49 +01:00
|
|
|
let d = Day01::init(strs);
|
2021-12-01 17:07:17 +01:00
|
|
|
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");
|
2021-12-01 20:53:49 +01:00
|
|
|
let d = Day01::init(strs);
|
2021-12-01 17:07:17 +01:00
|
|
|
assert_eq!("5", d.part2())
|
|
|
|
}
|
|
|
|
}
|