Front page | perl.fwp | Postings from November 2001

## Re: Daily Perl FAQ - How do I select a random line from a file? (fwd)

From:
Yanick
Date:
November 27, 2001 09:46
Subject:
Re: Daily Perl FAQ - How do I select a random line from a file? (fwd)
Message ID:
20011127124725.A16171@gilgamesh.sympatico.ca
```On Tue, Nov 27, 2001 at 11:31:39AM -0600, Andy Bach wrote:
> Okay, would the maths folk like to offer a helpful explanation?

Sure.

> Question:
> How do I select a random line from a file?
>
>     Here's an algorithm from the Camel Book:
>
>         srand;
>         rand(\$.) < 1 && (\$line = \$_) while <>;

It's easy to see if you begin by the end. Let's say,
to keep things simples, that your file has 100 lines.

What is the probability that \$line ends up being
the last line of your file? Well, it will be the
case if rand(100) < 1 (\$. being the current line number),
which happens with prob. 1/100.

What is the probability that \$line ends up being
the second last line of your file? It's going to happen
if \$line gets that line (prob. 1/99) AND the last line
is not chosen (pro. 99/100), so 1/99 * 99/100 = 1/100.

The prob. that \$line ends up being the third last line?
Must chose that line (1/98) AND not chose the next two ones
(98/99 and 99/100), so 1/98 * 98/99 * 99/100 = 1/100.

And so on and so forth.

Joy,
`/anick

--
print map { ( split '', 'P arctehYkl.no' )[ hex ] }
split '', '86512cd57631063a1724963b';

```