## Perl Weekly Challenge 246: 6 out of 49

These are some answers to the Week 246, Task 1, of the Perl Weekly Challenge organized by Mohammad S. Anwar.

Spoiler Alert: This weekly challenge deadline is due in a few days from now (on December 10, 2023 at 23:59). This blog post provides some solutions to this challenge. Please don’t read on if you intend to complete the challenge on your own.

## Task 1: 6 out of 49

6 out of 49 is a German lottery.

Write a script that outputs six unique random integers from the range 1 to 49.

Output:

``````3
10
11
22
38
49
``````

For space reasons, we will display the random integers on the same line. Also, it appears that the integers in the example above are sorted in ascending order. It would be very easy to sort the output, but we will not do it, since it is not part of the specification for the task. Also, note that we need six unique integers (i.e. without repetition).

### 6 out of 49 in Raku

This is very easy in Raku, since the built-in pick method returns the specified number of elements chosen at random and without repetition from the invocant.

``````say (1..49).pick: 6;
``````

This program displays the following output:

``````\$ raku ./german-lottery.raku
(40 36 17 9 41 25)
``````

Of course, the program is so simple that we can run it as a Raku one-liner at the command line:

``````\$ raku -e 'say (1..49).pick: 6;'
(44 10 18 12 46 21)
``````

### 6 out of 49 in Perl

This is slightly more complex in Perl, because we need to transform the numbers generated into integers and to prevent the generation of duplicates. We use a hash to store the result, and add integers to the hash only when the integer has not been seen before.

``````use strict;
use warnings;
use feature 'say';

my %result;
while (%result < 6) {
# get random integers in the range 1..49
my \$rand = int( rand 49) + 1;
\$result{\$rand} = 1 unless exists \$result{\$rand};
}
say join " ", keys %result;
``````

Running the program a few times displays the following output:

``````\$ perl ./german-lottery.pl
18 33 43 31 44 41

~
\$ perl ./german-lottery.pl
45 49 15 19 37 43

~
\$ perl ./german-lottery.pl
16 3 23 26 31 9

~
\$ perl ./german-lottery.pl
27 48 1 8 40 24
``````

## Wrapping up

The next week Perl Weekly Challenge will start soon. If you want to participate in this challenge, please check https://perlweeklychallenge.org/ and make sure you answer the challenge before 23:59 BST (British summer time) on December 17, 2023. And, please, also spread the word about the Perl Weekly Challenge if you can.