mona
mona

Reputation: 123

generating 10 random matrix with 0 and specific number of 1

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

Upvotes: 4

Views: 711

Answers (1)

Szabolcs
Szabolcs

Reputation: 25703

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.)

Upvotes: 11

Related Questions