Course of Raku / Addendum 🆕 / Working with data / Lists, arrays, and hashes / Exercises / The most common element
Solution: The most common element
Here is a possible solution to the task.
Code
my @values = <a b a c a b>;
my %count;
%count{$_}++ for @values;
say %count.sort(-*.value)[0].key;🦋 You can find the source code in the file most-common.raku.
Output
aComments
After tallying each value in
%count, sorting the pairs by-*.valueputs the most frequent first;[0].keythen gives back that element.Raku can do the tallying for you with a
Bag, which counts how many times each value appears. Then.max(*.value)picks the pair with the highest count, and.keyis the element itself:my @values = <a b a c a b>; say @values.Bag.max(*.value).key; # a
The whole tally is a single method call, and there is no explicit hash to manage.