Hi All,
I have a Vec<f32>
and I want to get the sum, max, min, max_index and min_index. I can do all this with Itertools
minmax()
and position_minmax()
but that needs three pass. Other suggestion is to use std like max()
, position()
and min()
but that also needs more than 1 pass. Hence, I wrote the below code,
fn main() {
let items = [20.0, 4.1, 1.1, 17.2, -33.7, 21.6];
let (max, max_index, min, min_index, sum) = items
.iter()
.enumerate()
.fold((items[0], 0, items[0], 0, 0.0), |acc, (index,&x)| {
let max;
let min;
let max_index;
let min_index;
let sum;
if x > acc.0 {
max = x;
max_index = index;
} else {
max = acc.0;
max_index = acc.1;
}
if x < acc.2 {
min = x;
min_index = index;
} else {
min = acc.2;
min_index = acc.3;
}
sum = acc.4 + x;
(max, max_index, min, min_index, sum)
});
println!("{}, {}", max, max_index);
println!("{}, {}", min, min_index);
println!("{}, {}", sum, sum as f32 / items.len() as f32);
}
Is it possible to write this in idiomatic way?