xun*_*ang 2 c c++ random algorithm random-sample
我想生成一个具有固定稀疏性和随机索引和值的矩阵.
为了简化问题,以数组为例:生成一个只有3个非零值位置的arr [10].如果我只是逐个随机选择这3个索引,那么算法的效率就会因为重复而变坏.
更难,我还想生成一个排名为k的随机矩阵,因为空cols和行可能会导致我的代码出错...这次如何制作?
谢谢!
你可以用STL的random_shuffle完成这个:
#include <vector>
#include <algorithm>
// Function that generates random array elements
int random_element();
const int n = 10; // Size of the array
const int k = 4; // Number of random (non-zero) elements in the array
int a[n]; // The array, filled with zeros
int main()
{
for (size_t i = 0; i < k; ++i)
a[i] = random_element();
std::random_shuffle(a, a + n);
// Now 'a' contains k random elements and (n-k) zeros, in a random order
}
Run Code Online (Sandbox Code Playgroud)