in reply to Re (tilly) 2 (unrandomness): Extract random records from text file
in thread Extract random records from text file

Or you can just shuffle them from the start:
my $num = shift; my @init = (0..$num-1); my @questions; while (<>) { $questions[splice @init, rand(@init), 1] = $_, next if $. <= $num; my $i = rand($.); $questions[$i] = $_ if $i < $num; }
  • Comment on Re: Re (tilly) 2 (unrandomness): Extract random records from text file
  • Download Code

Replies are listed 'Best First'.
Re (tilly) 4 (unrandomness): Extract random records from text file
by tilly (Archbishop) on Oct 03, 2001 at 21:30 UTC
    I prefer shuffling at the end using Fischer-Yates. Shuffling at the start with splice is algorithmically very bad. OK, with only 10 elements, it works just fine, but I tend avoid splice on general principle if there is a more efficient alternative. (Which there is in this case.)