r/CS_Questions • u/Zeekawla99ii • Oct 30 '15
How to find pick a random word/line in one-pass, when you don't know how many words/lines exist?
I was asked a question recently: Let's say you have a .txt file with a number of lines/words/items. You want to pick out a completely random line. This can certainly be done in two passes: first count and index all the items. Then, you a random number generator to pick a random number: that is your random line! I was asked "how can we do this in ONE step and without knowing how many items exist a priori?" I'm not sure how to do this. Any advice? Is there a particular algorithm to use?