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 - Scala Tutorial
From the course: Coding Exercises: Scala
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?…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.
Contents
-
-
-
Palindrome detector2m 15s
-
(Locked)
Password checker4m 20s
-
(Locked)
Colored boxes2m 15s
-
(Locked)
System properties1m 17s
-
(Locked)
Resistor tolerance2m 36s
-
(Locked)
Snakes and camels1m 58s
-
(Locked)
Stuff the stats sheet5m 50s
-
(Locked)
A slice of Pi5m 13s
-
(Locked)
Cron and regular expressions4m 35s
-
(Locked)
Reservoir sampling4m 55s
-
(Locked)
Evaluate a decision tree3m 3s
-
(Locked)
Calculator2m 41s
-
(Locked)
Error handling2m 58s
-
(Locked)
Sierpinski Triangle2m 2s
-
(Locked)
Rocketship7m 16s
-