Is there a Rust function which counts frequencies in a Vec?

Viewed 554

I want to count the frequencies of all elements in a given Vec, e.g. something like

count_frequencies(vec![1,1,1,4,1,2,3,5,4])

should return the following Vec:

[(1,4), (2,1), (3,1), (4,2), (5,1)]

(the order does not matter). While I know how I could implement such a function, it seems to me like there should already be an existing implementation in some crate. After some googling, I only found a crate named frequency, but didn't find any example in the documentation.

So, my question is: is there a crate that can achieve this task and, if so, how can I use it?

Edit: If you as well know a function which goes in the other direction, I would also be interested in that :)

2 Answers

Itertools offers counts, but you'd have to convert the result (a HashMap) into a Vec yourself.

Alternatively, sort the vector (costs O(n log n), but may - in practice - be faster than a HashMap-based approach) and use dedup_with_count on the sorted vector.

It isn't really needed because it is one-liner anyway:

    let frequencies = v
          .iter()
          .copied()
          .fold(HashMap::new(), |mut map, val|{
              map.entry(val)
                 .and_modify(|frq|*frq+=1)
                 .or_insert(1);
              map
          });

There are different requirements for different tasks so there is no need to make some standard method for this.

Related