Imagine items flying past you one at a time: tweets in a firehose, log lines from a server, cards being dealt face-up and then burned. You want to keep a fair random sample of, say, one item — every item that ever passes should have an equal chance of being the one you end up holding.
Easy, if you can store everything: collect the whole list, count it, then pick a random index. But here's the catch — you can only look at each item once, you can't store the stream, and you don't even know how long it is. It might stop after 10 items or after 10 billion.
That sounds impossible. How can every item be equally likely when you have to decide what to keep before you know how many items there are? The answer is a tiny, beautiful algorithm called reservoir sampling, and it gets the probabilities exactly right.
Comments
Loading comments...