Exactly how this works is complicated.
No, it isn't. How it works is as follows: we read a file, line by line. For the kth line read, we decide with probability 1/k whether we remember the line, forgetting any previous one.

That's fairly trivial. It takes just a little analysis to see it's fair. Fair means that any line will be the final pick. So, what's the probability of line k to be the final pick? First what needs to be happen is that it gets remembered when the line is read, which has a probability of 1/k. Then, any next lines must *not* be picked. For each of the next lines, this happens with probability (j -1)/j, where j is the line number. Since all those probabilities are independent of each other, we can multiply them:

           n
        -------
    1    |   |    j-1        1     k      1 
   ---   |   |    ---   ==  --- * --- == ---
    k    |   |     j         k     n      n
         j=k+1
Too bad we can't really do math in HTML.

In reply to Re^2: Opening random files then reading random lines from file. by JavaFan
in thread Opening random files then reading random lines from file. by fame

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.