Fast random selection algorithm

Given an array of true / false values, which most efficient algorithm selects an index with a true value in random order.

Simple sketch algorithm

a <- the array
c <- 0
for i in a:
    if a[i] is true: c++
e <- random number in (0, c-1)
j <- 0
for i in e:
    while j is false: j++
return j

Can anyone come up with a faster algorithm? Maybe there is a way to only go through the list once, even if the number of true elements is unknown at the beginning?

+3
source share
2 answers

Use the "select a random item from an infinite list" algorithm.

Keep a pointer to the current selection, as well as the number of valid values ​​that you saw.

, , P = (1/count). ( , , ... , 1/2, 1/3 ..)

. ( , .) , , , .

. LINQ " "; .

+8

, true . O (n) .

+6

Source: https://habr.com/ru/post/1724630/


All Articles