Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print the hash elements by grouping their values in Raku

Tags:

hash

raku

I keep record of how many times a letter occur in a word e.g. 'embeddedss'

my %x := {e => 3, m => 1, b => 1, d => 3, s => 2};

I'd like to print the elements by grouping their values like this:

# e and d 3 times
# m and b 1 times
# s 2 times

How to do it practically i.e. without constructing loops (if there is any)?

Optional Before printing the hash, I'd like to convert and assing it to a temporary data structure such as ( <3 e d>, <1 m b>, <2 s> ) and then print it. What could be the most practical data structure and way to print it?

like image 436
Lars Malmsteen Avatar asked Sep 05 '20 12:09

Lars Malmsteen


Video Answer


1 Answers

Using .categorize as suggested in the comments, you can group them together based on the value.

%x.categorize(*.value)

This produces a Hash, with the keys being the value used for categorization, and the values being Pairs from your original Hash ($x). This can be looped over using for or .map. The letters you originally counted are the key of the Pairs, which can be neatly extracted using .map.

for %x.categorize(*.value) {
    say "{$_.value.map(*.key).join(' and ')} {$_.key} times";
}

Optionally, you can also sort the List by occurrences using .sort. This will sort the lowest number first, but adding a simple .reverse will make the highest value come first.

for %x.categorize(*.value).sort.reverse {
     say "{$_.value.map(*.key).join(' and ')} {$_.key} times";
}
like image 145
Tyil Avatar answered Oct 21 '22 01:10

Tyil