To count the no.of times an element occurs in a vector.
For example :
let v = vec![1,1,1,1,2,2,3,3,4];
I would like to know the count of 1,2,3,4 as 4,2,2,1 respectively.
One approach I found was:
v.iter().filter(|&n| *n == 1).count()
If any other ways possible, please suggest me !!!
H2CO3
May 23, 2020, 5:09am
2
What's wrong with .filter().count()
?
How to get maximum repeated element in the vector using only functional programming or like without using any loops?
Do you know the max value ahead of time?
If you want to get all the frequencies in a single pass, you can store them in some sort of map, like a HashMap:
let mut m: HashMap<i32, usize> = HashMap::new();
for x in v {
*m.entry(x).or_default() += 1;
}
Then, iterate over the map to find the key with the highest value:
let max = m.into_iter().max_by_key(|(_, v)| *v).map(|(k, _)| k);
(Playground )
If you don't like for
loops, you can use fold
instead, though I don't think this particularly makes it more "functional." It's just a different way of writing the same loop.
let max = v.into_iter()
.fold(HashMap::<i32, usize>::new(), |mut m, x| {
*m.entry(x).or_default() += 1;
m
})
.into_iter()
.max_by_key(|(_, v)| *v)
.map(|(k, _)| k);
(Playground )
5 Likes
system
Closed
August 21, 2020, 5:17pm
8
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.