From bb990ebffc3044fc0eb975a225ca6541c61f7f69 Mon Sep 17 00:00:00 2001 From: cos Date: Thu, 2 Dec 2021 12:00:15 +0100 Subject: Use trait to increase flexibility By using IntoIterator, the changed functions become more flexible in what input they accept. --- 2021/rust/day01/src/main.rs | 21 ++++++++++++--------- 2021/rust/day02/src/main.rs | 4 ++-- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/2021/rust/day01/src/main.rs b/2021/rust/day01/src/main.rs index a3a6e73..559f98c 100644 --- a/2021/rust/day01/src/main.rs +++ b/2021/rust/day01/src/main.rs @@ -31,16 +31,16 @@ enum Change { Identical, } -fn count_increases(values: &[usize]) -> usize { - let changes: Vec = values.iter().scan(None, |state, val| { +fn count_increases<'a, I: IntoIterator>(values: I) -> usize { + let changes: Vec = values.into_iter().scan(None, |state, val| { let next = match state { None => Change::NoPrevVal, - Some(prev) if val < prev => Change::Decreased, - Some(prev) if val > prev => Change::Increased, - Some(prev) if val == prev => Change::Identical, + Some(prev) if val < *prev => Change::Decreased, + Some(prev) if val > *prev => Change::Increased, + Some(prev) if val == *prev => Change::Identical, Some(_) => unreachable!(), }; - *state = Some(*val); + *state = Some(val); Some(next) }).collect(); @@ -49,14 +49,17 @@ fn count_increases(values: &[usize]) -> usize { ) } -fn part1(input: &[usize]) -> Result { +fn part1<'a, I: IntoIterator>(input: I) -> Result { let count = count_increases(input); Ok(count) } -fn part2(input: &[usize]) -> Result { - let slidesums: Vec<_> = input.iter().zip(input[1..].iter()).zip(input[2..].iter()).map(|n| { +fn part2<'a, I: IntoIterator + Copy>(input: I) -> Result { + let left_iter = input.into_iter(); + let middle_iter = input.into_iter().skip(1); + let right_iter = input.into_iter().skip(2); + let slidesums: Vec<_> = left_iter.zip(middle_iter).zip(right_iter).map(|n| { let ((first, second), third) = n; first + second + third }).collect(); diff --git a/2021/rust/day02/src/main.rs b/2021/rust/day02/src/main.rs index 4178ecc..d093dba 100644 --- a/2021/rust/day02/src/main.rs +++ b/2021/rust/day02/src/main.rs @@ -91,7 +91,7 @@ fn read_input>(filename: T) -> Result> { ).collect() } -fn part1(input: &[Command]) -> Result { +fn part1<'a, I: IntoIterator>(input: I) -> Result { let mut position = Position { x: 0, y:0 }; for command in input { match command { @@ -104,7 +104,7 @@ fn part1(input: &[Command]) -> Result { Ok(position) } -fn part2(input: &[Command]) -> Result { +fn part2<'a, I: IntoIterator>(input: I) -> Result { let mut position = Position { x: 0, y:0 }; let mut aim = 0; for command in input { -- cgit v1.2.3