How to get a randomly selected hash key in Perl 6?

A quick and hopefully simple question:

I need tools to randomly select from a given set of hash keys. The perl6.org documentation on neither rand nor hash offers a lot of advice.

my %a = 1,2,3,4,5,6; 

Given the foregoing,

 %a.keys; 

returns (5 1 3) , and if I just try

 %a.rand; 

I get a pseudo-random float, and not just any one key.

In the end, I collected %a.keys[Int(%a.elems.rand)] , but was hoping for something simpler.

+5
source share
2 answers

Use pick or roll e.g.

 %a.keys.pick 
+9
source

As always, Christoph's answer is correct (he knows Perl 6 well). Nevertheless, I thought that I would work a little with pick and roll can be easily confused in the first place.


If you only need one random key, pick and roll seem the same and can be used interchangeably:

 my $rand-keyA = %a.keys.pick; my $rand-keyB = %a.keys.roll; 

However, think pick as “I have N things and I take them out of the container, and as soon as they disappear, they left (for this choice)” compared to roll as “I have an N-way game that I ride "

 say %a.keys.pick(2); # (5 3) say %a.keys.pick(2); # (3 1) say %a.keys.pick(5); # (3 5 1) no more, because there were only three to pick from say %a.keys.pick(10); # (3 1 5) say %a.keys.roll(5); # (1 5 1 5 3) as many "rolls" as you request say %a.keys.roll(10); # (5 5 1 1 5 5 3 1 3 1) 

pick(*) is an easy way to create a random list of orders from an array without having to know how many elements are in it:

 my @array = <foo bar baz foobar>; @array.pick(*); # (bar foobar baz foo) 

roll(*) is an easy way to create an infinite list whose elements were randomly selected from the original array:

 my @rolls = @array.roll(*); say @rolls[0]; # foobar say @rolls[10]; # bar say @rolls[351]; # baz say @rolls[19123]; # foobar say @rolls[1000000]; # bar say @rolls[1000001]; # bar say @rolls[1000002]; # foo 
+6
source

Source: https://habr.com/ru/post/1241862/


All Articles