-
Notifications
You must be signed in to change notification settings - Fork 0
/
day1.rs
52 lines (46 loc) · 1.22 KB
/
day1.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
use super::util;
use std::error::Error;
use std::vec::Vec;
pub fn part1<'a, I, S>(lines: I) -> Result<usize, Box<dyn Error + Send + Sync>>
where
I: IntoIterator<Item = &'a S>,
S: AsRef<str> + 'a,
{
let nums: Vec<i32> = util::parse_many(lines)?;
Ok(nums
.iter()
.zip(nums.iter().skip(1))
.filter(|(x, y)| x < y)
.count())
}
pub fn part2<'a, I, S>(lines: I) -> Result<usize, Box<dyn Error + Send + Sync>>
where
I: IntoIterator<Item = &'a S>,
S: AsRef<str> + 'a,
{
let nums: Vec<i32> = util::parse_many(lines)?;
let sums: Vec<i32> = nums.windows(3).map(|w| w.iter().sum()).collect();
Ok(sums
.iter()
.zip(sums.iter().skip(1))
.filter(|(x, y)| x < y)
.count())
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
static EXAMPLE: &[&str] = &[
"199", "200", "208", "210", "200", "207", "240", "269", "260", "263",
];
#[test]
fn part1_examples() -> Result<(), Box<dyn Error + Send + Sync>> {
assert_eq!(7, part1(EXAMPLE)?);
Ok(())
}
#[test]
fn part2_examples() -> Result<(), Box<dyn Error + Send + Sync>> {
assert_eq!(5, part2(EXAMPLE)?);
Ok(())
}
}