algorithm - 水库取样

标签 algorithm random reservoir-sampling

为了从大小不确定的数组中检索 k 个随机数,我们使用了一种称为水库采样的技术。任何人都可以用示例代码简要地强调它是如何发生的吗?

最佳答案

我实际上并没有意识到这个有一个名字,所以我从头开始证明并实现了这个:

import random
def random_subset( iterator, K ):
    result = []
    N = 0

    for item in iterator:
        N += 1
        if len( result ) < K:
            result.append( item )
        else:
            s = int(random.random() * N)
            if s < K:
                result[ s ] = item

    return result

发件人:http://web.archive.org/web/20141026071430/http://propersubset.com:80/2010/04/choosing-random-elements.html

在接近尾声时给出证明。

关于algorithm - 水库取样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2612648/

相关文章:

python - 压缩大量相似的字符串

algorithm - 我找不到这个 6*6 矩阵的模式

c++ - 无法理解为什么我的程序会抛出错误

c - 如何在 C 中创建随机字符串数组?

python - 迭代或惰性水库采样

java - 通过 1 遍查找链表的中间元素,这是创意 "useless answer"吗?

language-agnostic - 高尔夫代码:幽灵腿

javascript随机8位特定数字

algorithm - 常量内存库采样,O(k) 可能吗?