生成t个随机位的位向量

生成t个随机位的位向量

本文介绍了生成t个随机位的位向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成大小为p的数组/向量v,其中t为1,p-t为零. t的位置必须是随机的.

I want to generate an array/vector v of size p with t ones and p-t zeros. The position of the t ones must be random.

这是我到目前为止编写的解决方案,但是我不确定这是否是最有效的解决方案.另外,我从未使用过random_devicemt19937(在此处找到它们)以前,所以我不知道可能有什么弊端.

This is the solution that I've written so far, but I'm not sure if it's the most efficient one. In addition I never used random_device or mt19937 (found them here) before, so I don't know what are the possible drawbacks.

#include <algorithm>
#include <random>
#include <vector>
...
int p=10, t=3;
std::vector<int> v(p,0);
for(int i=0;i<t;i++)  //better way?
    v[i] = 1;
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(std::begin(v), std::end(v), g);

这是我要重现的matlab代码:

This is the matlab code that I'm trying to reproduce:

rp = randperm(p);
I_s(i,:) = rp(1:t);
v = zeros(p,1);
v(I_s(i,:)) = 1;

在此处演示!

推荐答案

std::shuffle(std::begin(v), std::end(v), g);

不将位的位置随机化,它只是随机更改矢量中现有项(所有位置都设置为零位)的位置.

Doesn't make the bit position random, it just changes the positions of the existing items (which all have the zero position bit set) in the vector randomly.

如果我正确理解了您的要求,那么您实际上应该拥有的东西是这样的:

If I understood your requirement correctly, What you actually should have is something like:

std::random_device rd;
std::mt19937 g(rd());
for(int i=0;i<t;i++)
     v[i] = 1 << rd(); // set a random bit position

这篇关于生成t个随机位的位向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 18:11