如何对0,1,..中的k个随机数进行采样..,n-1,而不缓存到数组
How to sample k random numbers in 0, 1, ..., n-1 without caching to an array
我想对0、1、2、…中的k个不同的随机数进行采样(无需替换(。。。,n-1.
在我看来,我在网上找到的大多数解决方案都需要一个数组来存储所有数字,然后以某种方式打乱数组。然而,它需要O(n(空间。我想知道在C++中是否有任何不生成数组的方法。
确定
它被称为储层取样。基本上,你假装你得到的值是0,1,2。。。,从流中抽取n-1,对随机数进行采样并与储层进行交换。
曾经是一个伪代码,调试过它,现在它应该只工作
#include <iostream>
#include <random>
#include <vector>
static int N = 0;
static int s = 0;
int next_item() { // emulate incoming with the stream
if (s == N) // all values are streamed
return -1;
return s++;
}
std::vector<int> RS(int k) {
std::vector<int> result;
std::mt19937 rng(987654321);
int sp = 0; // position in the stream
for (;; ) {
int v = next_item();
if (v < 0)
break;
if (sp < k)
result.push_back(v);
else
{
std::uniform_int_distribution<int> uni(0, sp);
int idx = uni(rng);
if (idx < k)
result[idx] = v;
}
++sp;
}
return result;
}
int main() {
s = 0;
N = 10000;
auto v = RS(10);
for (auto e : v) {
std::cout << e << "n";
}
return 0;
}
相关文章:
- 如何用RISC-V GD32VF103CBT6开发板卸载精确的ADC过采样
- 如何使用采样器立方体作为数组
- 多重采样背景不显示
- 如何从wav文件中获取采样率?
- 如何对0,1,..中的k个随机数进行采样..,n-1,而不缓存到数组
- 如何在直接 x12 上使用多重采样
- 为什么当我选择>250000个采样点时,程序不起作用?
- 点云下采样和使用 PCL 进行正态估计
- 片段着色器中的"错误:在 GLSL 1.30 及更高版本中禁止使用非常量表达式索引的采样器数组"
- 在glTexImage2D中,当我选择与在着色器中采样不同的内部格式时,情况如何?
- 使用哪个 pcl 滤波器对点云进行下采样
- 使用膨胀卷积的语义分割中的上采样
- 为什么找不到这个统一采样器2D?
- 如何在保持最小距离的同时沿有限线随机采样
- 使用GlblitFrameBuffer进行多样采样,无法使用OpenGL ES 3.0
- 如何将多个立方体纹理传递到均匀的采样器中
- 多采样框架渲染对象和深度缓冲区
- GLSL 无法获取采样器3D 值
- 对随机序列进行降采样会降低随机性吗?有没有原理/定理来证明这一点?
- 在未填充为 4 字节的 3 通道上进行图像重采样