Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would you pick a uniform random element in linked list with unknown length?

How would you pick a uniform random element in linked list with unknown length in one pass or if not two passes?

like image 343
exlux15 Avatar asked Feb 22 '12 19:02

exlux15


1 Answers

Use reservoir sampling http://en.wikipedia.org/wiki/Reservoir_sampling . You need only one pass of the data.

For picking one element:

  1. Pick first element (probability 1)
  2. Later, for kth element pick it with probability 1/k (i.e. replace the existing selection with kth element)

I will let you prove that this results in uniform selection of elements.

like image 146
ElKamina Avatar answered Oct 25 '22 10:10

ElKamina