Given an unknown length list, return a random item in it by scanning it only 1 time

前端 未结 4 628
北海茫月
北海茫月 2021-01-23 05:37

Given an unknown length list, return a random item in it by scanning it only 1 time.

My idea:

A similar algorithm is Reservoir Sampling (posted by others). But

4条回答
  •  醉梦人生
    2021-01-23 06:25

    See the Perl cookbook for the algorithm, which you'll easily adapt to C++.

    Basically, scan the list once, and for each entry with index i you read, keep it if a random number between 0 and i+1 is less than 1.

    The result is the last entry kept.

提交回复
热议问题