The weekly challenge 246 - Task 1: 6 out of 49
1 #!/usr/bin/perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-246/#TASK1 3 # 4 # Task 1: 6 out of 49 5 # =================== 6 # 7 # 6 out of 49 is a German lottery. 8 # 9 # Write a script that outputs six unique random integers from the range 1 to 10 # 49. 11 # 12 ## Output 13 ## 14 ## 3 15 ## 10 16 ## 11 17 ## 22 18 ## 38 19 ## 49 20 # 21 ############################################################ 22 ## 23 ## discussion 24 ## 25 ############################################################ 26 # 27 # Collect random numbers until we have 6 of them. In case we randomly select a 28 # number that we saw already, discard the number and select another random 29 # number instead. 30 # 31 use strict; 32 use warnings; 33 34 my $result = {}; 35 36 sub next_rand { 37 my $n = int(rand(49)) + 1; 38 return $n unless $result->{$n}; 39 # print "Collision, need another random number!\n"; 40 return next_rand(); 41 } 42 43 foreach(1..6) { 44 my $n = next_rand(); 45 $result->{$n} = 1; 46 } 47 48 print join("\n", sort {$a<=>$b} keys %$result), "\n"; 49