Generating 10 random matrices with 0 and a specific number 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 I can indicate that in each matrix I need the same number 1, for example 5. I thought about to put a variable that counts the number 1, and if they are less than or greater than 5, to adjust the matrix, but I was wondering if there is a much faster solution. Thanks

+4
source share
1 answer

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

(I usually use this to create adjacency matrices for random graphs with a fixed number of edges.)

+11
source

Source: https://habr.com/ru/post/1379975/


All Articles