in reply to Approach to efficiently choose a random line from a large file

This came up some time ago on the QOTW list. As others mentioned, the approach you're taking is biased based on line length (a line with 80 characters is twice as likely to be chosen as one with 40 characters). There is another approach that has no bias, but also no bound on runtime, although in practice it should be pretty fast. Basicall, seek to a random byte, and if that byte is a newline character, use the line immediately following it. (If it's the newline at the end of the file, use the first line instead.) If it's not, seek again. Expected time is the average length of the lines (if each line is 20 characters, you'd expect to hit a newline one out of 20 tries), but there's no guarantee you won't be very unlucky and spend forever without hitting one (for suitibly large values of "forever"). But it is an unbiased way of doing it without reading the entire file.
  • Comment on Re: Approach to efficiently choose a random line from a large file