Choose random array element satisfying certain property

后端 未结 5 1590
隐瞒了意图╮
隐瞒了意图╮ 2020-12-16 15:34

Suppose I have a list, called elements, each of which does or does not satisfy some boolean property p. I want to choose one of the elements that

5条回答
  •  误落风尘
    2020-12-16 16:19

    In The Practice of Programming, pg. 70, (The Markov Chain Algorithm) there is a similar algorithm for that:

    [...]
      nmatch = 0;
      for ( /* iterate list */ )
        if (rand() % ++nmatch == 0) /* prob = 1/nmatch */
          w = suf->word;
    [...]
    

    "Notice the algorithm for selecting one item at random when we don't know how many items there are. The variable nmatch counts the number of matches as the list is scanned. The expression

    rand() % ++nmatch == 0
    

    increments nmatch and is then true with probability 1/nmatch."

提交回复
热议问题