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
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With