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?
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 " "; .
, true . O (n) .
true
Source: https://habr.com/ru/post/1724630/More articles:What is this for a loop? - c ++Writing a daemon in lens c - objective-cUsing static data structures for DMA - linux-kernelThe reason for the special streamlining of division and multiplication in C ++ is c ++How to show hints in Qt - qtUsing external joins in HQL queries - javaLess defined generics in C #? - collectionsIE addon development in .net - internet-explorerWith Git, how can I make some changes to the working copy in another branch? - gitWhy do I get a 403 ban when I call an external IIS-based MVC that returns a JSON result - jqueryAll Articles