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
53
54
55
56
57
58
59
60
61
62
use num_traits::ToPrimitive;
pub struct AveragedCollection<T: ToPrimitive + Copy> {
values: Vec<T>,
average: f64,
}
impl<T> AveragedCollection<T>
where T: ToPrimitive + Copy {
pub fn new() -> AveragedCollection<T> {
AveragedCollection {
values: Vec::new(),
average: 0.0,
}
}
pub fn add(&mut self, value: T) {
self.values.push(value);
self.update_average();
}
pub fn remove(&mut self) -> Option<T> {
match self.values.pop() {
Some(value) => Some(value),
None => None,
}
}
pub fn average(&self) -> f64 {
self.average
}
fn update_average(&mut self) {
let mut total: f64 = 0.0;
for value in &self.values {
total += ToPrimitive::to_f64(value).unwrap();
}
self.average = total as f64 / self.values.len() as f64;
}
}