in reply to Where is the zero coming from?

And if this wasn't a homework question, the standard | kneejerk approach would be List::Util::shuffle (if: the list you're shuffling is relatively small; you don't necessarily need robust randomness, because shuffle is based on the rand functions in the libc library against which your Perl is built, and they may not be terribly random :).

c:\@Work\Perl\monks>perl -wMstrict -le "use List::Util qw(shuffle); ;; use constant N => 6; use constant LIST => (1 .. 49); use constant FMT => ' %02d' x N; ;; for my $pick (1 .. 5) { my @picks = sort { $a <=> $b } (shuffle LIST)[0 .. N-1]; printf qq{pick %2d: ${ \FMT } \n}, $pick, @picks; } " pick 1: 01 05 15 34 38 39 pick 2: 11 20 22 31 38 48 pick 3: 11 15 18 21 22 29 pick 4: 05 07 09 12 20 48 pick 5: 01 13 16 24 44 45

Replies are listed 'Best First'.
Re^2: Where is the zero coming from?
by BillKSmith (Monsignor) on Aug 02, 2014 at 14:57 UTC
    I believe that this is the only suggestion which correctly simulates picking six balls without putting each ball back in the box before drawing the next ball. (Most lotteries keep the balls out and display all six of them.)
    Bill

      Although I haven't tested it, I think CountZero's approach avoids dupes: splice removes each spliced element from the  @choices source array before the next pick. I like CountZero's approach better because it's simple, doesn't depend on a module, and seems like it would scale well to very large arrays. The only drawback I see is that the source array is mutated. However, I believe there is a large literature base on 'fair' picking, so there's probably an even better solution!