选择随机数组元素满足某些财产 [英] Choose random array element satisfying certain property

查看:136
本文介绍了选择随机数组元素满足某些财产的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个表,名为元素,其中每个或不符合某些布尔属性 P 。我想选择的要素之一是满足 P 随机均匀分布。我不知道时间提前很多项目如何满足这个属性 P

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 satisfies p by random with uniform distribution. I do not know ahead of time how many items satisfy this property p.

将以下code做到这一点:

Will the following code do this?:

pickRandElement(elements, p)
     randElement = null
     count = 0
     foreach element in elements
          if (p(element))
               count = count + 1
               if (randInt(count) == 0)
                    randElement = element

     return randElement

randInt(N)返回一个随机INT K 0℃= K< N

(randInt(n) returns a random int k with 0 <= k < n.)

推荐答案

它的工作原理数学。可以通过感应来证明。

It works mathematically. Can be proven by induction.

显然,当n = 1元满足p。

Clearly works for n = 1 element satisfying p.

有关的n + 1个元素,我们将选择元件的n + 1的概率是1 /(N + 1),所以它的概率是确定。但是,这是如何影响选择前n个元素之一的结束概率是多少?

For n+1 elements, we will choose the element n+1 with probability 1/(n+1), so its probability is OK. But how does that effect the end probability of choosing one of the prior n elements?

每个事先n个有被选择的概率为1 / n的机会,直到我们发现了元素n + 1。现在,发现n + 1个以后,有一个1 /(N + 1)的机会,元素的n + 1被选择,所以有一个/(N + 1)的机会,所述previously选择元件保持选择。这意味着被n + 1个发现后所选择的它的最终概率为1 / N *(N / N + 1)= 1 / N + 1 - 这是对所有的n + 1个元素均匀分布,我们希望的概率。

Each of the prior n had a chance of being selected with probability 1/n, until we found element n+1. Now, after finding n+1, there is a 1/(n+1) chance that element n+1 is chosen, so there is a n/(n+1) chance that the previously chosen element remains chosen. Which means its final probability of being the chosen after n+1 finds is 1/n * (n/n+1) = 1/n+1 -- which is the probability we want for all n+1 elements for uniform distribution.

如果它当n = 1,它适用于N + 1给出了n,那么它适用于所有的n。

If it works for n = 1, and it works for n+1 given n, then it works for all n.

这篇关于选择随机数组元素满足某些财产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆