On Wed, 2003-12-10 at 11:12, David Garamond wrote:
> I'm trying to extend the Perl cookbook recipe on how to pick a random
> line from a file:
>
> #!/usr/bin/perl
> rand($.) < 1 && ($line = $_) while <>;
> print $line;
>
> for picking up to N random lines from a file:
>
> ------------start code--------------
> #!/usr/bin/perl
>
> die "Usage: $0 <N>, where N is the number of lines to pick\n"
> if @ARGV < 1;
> $N = shift @ARGV;
>
> @pick = ();
> while (<>) {
> if (@pick < $N) {
> push @pick, $_;
> ($r1, $r2) = (rand(@pick), rand(@pick));
> ($pick[$r1], $pick[$r2]) = ($pick[$r2], $pick[$r1]);
> } else {
> rand($.) <= $N and $pick[rand(@pick)] = $_;
> }
> }
>
> print @pick;
> -------------end code---------------
>
> Could anyone verify if the algorithm is correct?
Dave,
Yes, your algorithm seems to work. I just made a file with a number
(1-20) on each line, then ran it and it seems to work just fine.
HTH,
Kevin
--
Kevin Old <[EMAIL PROTECTED]>
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>