Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generating 10 random matrix with 0 and specific number of 1

Tags:

c++

visual-c++

I created a function to create a random matrix containing 0 and 1 in C++ using srand and rand but i didn't know how can I specify that in each matrix i need the same number of 1 for example 5. I thought of putting a variable that counts the number of 1 and if they are less or more then 5 to adjust the matrix, but i was wondering if there's a much faster solution.thanks

like image 286
mona Avatar asked Dec 21 '22 06:12

mona


1 Answers

Create a vector with the same number of elements as the matrix, containing the appropriate number of 1s at the beginning, and all 0s at the end. Then random_shuffle this vector, and copy the elements into a matrix.

(I routinely use this to generate adjacency matrices of random graphs with a fixed number of edges.)

like image 134
Szabolcs Avatar answered Dec 24 '22 01:12

Szabolcs