From the course: Coding Exercises: Scala

Unlock this course with a free trial

Join today to access over 25,300 courses taught by industry experts.

Reservoir sampling

Reservoir sampling

(gentle 8-bit video game music) - [Narrator] Reservoir sampling is a neat algorithm to sample an element from a collection when we don't know how many elements there are and we want to use only a single traversal of the collection. The trick is to keep account of the number of elements we've seen so far. And then we choose the current element with probability equal to one on the number of elements. This means we choose the first element with probability one on one: one. Choose the second element with probability one on two. The third element with probability one on three. And so on. When we get to the end of the collection, we'll have an element chosen with equal probability amongst all the elements. Your challenge is to implement reservoir sampling with the signature shown. Your method should accept a list of elements, which we're going to sample from and return an option of an element. Why do we return an option?…

Contents