For any given run of the program, do you only want to draw a single item, or are you wanting to draw items in succession? Are you trying to avoid having the entire list in memory? Do you know anything about the items in your list?

If you know the average string length of each item (or rather the distance between commas) and the size of the file, you can guess at how many items are in the file. Generate a uniformly distributed random integer, and then process the file until you find the item that you choose. If the file ends before you get there, you could either pick a new number (based upon how many items you now know are there), or start at the beginning (distribution is no longer strictly uniform however).

If you are going to pick items over and over, you might treat the problem like the interval of time between soldiers being kicked by horses (exponential waiting times, Poisson problems). You generate an exponential deviate and convert to integer. This is how many positions in the list you travel to get to the next item to pick. When you reach end of list, start at the beginning.


In reply to Re: Pick random item from list of unknown length? by Anonymous Monk
in thread Pick random item from list of unknown length? by Cody Fendant

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.