I worked on implementing a simple moving average function in Rust, that works on a collection of year/revenue tuples:
fn compute_moving_average(window: &Box<&[(u32, u32)]>) -> (u32, f32) {
let window_size = window.len();
let current_year = window
.iter()
.nth((window_size as f32/ 2.0).floor() as usize)
.unwrap().0;
let sum = window
.iter()
.fold(0, |a, x| a + x.1) as f32 / window_size as f32;
(current_year, sum)
}
fn extract_moving_average_for_year(year: u32, moving_average: &Vec<(u32, f32)>) -> Option<f32> {
let x = moving_average
.iter()
.find(|a| a.0 == year);
match x {
Some(a) => Some(a.1),
None => None,
}
}
fn merge_moving_average(a: (u32, u32), avg: Option<f32>) -> (u32, u32, Option<f32>) {
(a.0, a.1, avg)
}
fn main() {
let vec = vec![
(2003, 4),
(2004, 6),
(2005, 5),
(2006, 8),
(2007, 9),
(2008, 5),
(2009, 4),
(2010, 3),
(2011, 7),
(2012, 8),
];
let moving_average = vec
.windows(5)
.map(|a| compute_moving_average(&Box::new(a)))
.collect::<Vec<_>>();
vec
.iter()
.map(|a| merge_moving_average(*a, extract_moving_average_for_year(a.0, &moving_average)))
.inspect(|a| println!("{:?}", a))
.collect::<Vec<_>>();
}
Output:
(2003, 4, None)
(2004, 6, None)
(2005, 5, Some(6.4))
(2006, 8, Some(6.6))
(2007, 9, Some(6.2))
(2008, 5, Some(5.8))
(2009, 4, Some(5.6))
(2010, 3, Some(5.4))
(2011, 7, None)
(2012, 8, None)