One Cloud from a Day's Sky
By the time I packed up my cloud-spotting notebook, the sky had offered cumulus, stratus, cirrus and one rather handsome cumulonimbus. Suppose I want to choose one observation at random for a sketch, but I don’t know how long I’ll stay outside or how many clouds I’ll record.
Reservoir sampling solves that problem while keeping just one candidate. Keep the first observation. For observation number n, draw a random integer from 0 through n − 1 and replace the candidate if the draw is 0. Every observation then has the same chance of being chosen, even though the final count was unknown when the first cloud appeared.
Here are the draws fixed in advance so the example is repeatable. The values 1, 0 and 2 are valid draws for observations two, three and four respectively. Both programs print Cirrus.
fn main() {
let clouds = ["Cumulus", "Stratus", "Cirrus", "Cumulonimbus"];
let draws = [1, 0, 2];
let mut chosen = clouds[0];
for (cloud, draw) in clouds.iter().skip(1).zip(draws) {
if draw == 0 {
chosen = cloud;
}
}
println!("{chosen}");
}
choose :: a -> [(a, Int)] -> a
choose current [] = current
choose current ((cloud, draw) : rest) =
choose (if draw == 0 then cloud else current) rest
main :: IO ()
main = do
let clouds = ["Cumulus", "Stratus", "Cirrus", "Cumulonimbus"]
draws = [1, 0, 2]
putStrLn (choose (head clouds) (zip (tail clouds) draws))
The first cloud survives the second observation with probability 1/2, then the third with probability 2/3, and the fourth with probability 3/4. Multiply those chances and you get 1/4. Each later cloud also ends with a 1/4 chance.
The fixed draws make the example easy to inspect, but they aren’t a random sampler on their own. For a real observation log, generate each draw independently and uniformly over its changing range. The method needs only one retained observation and one pass, though it can’t later tell you which cloud was most common without keeping additional information.