Hi guys, I got a matrix and I want to fill it with random binary numbers (0,1) but I want a specified number of 1's, how can I do this? I know that I can use srand(time(0)) and rand()%2 but I want to know what function should I use to tell the program that I want to use for eg only 5 1's in my matrix
1. Fill it with zeros.
2. Put 5 1's into the first 5 available elements.
3. Swap mat[r1][c1] with mat[r2][c2] where the subscripts are randomly chosen.
4. Repeat step 3 for say N/2 steps (N is the number of elements in the matrix)
And how can I add numbers to matrix full of 0's and the number of 1's to follow a varialble?
for ex if I
cin >> x;
for (int i=0;i<n;i++)
for (int j=0;i<n;j++)
#include <iostream>
#include <random>
#include <algorithm>
int main()
{
const std::size_t N = 10 ;
int mtx[N][N] {} ; // initialise with all zeroes
int* first = mtx[0] ; // pointer to the first item of the 2d array
std::size_t x ;
std::cout << "enter number of 1's [0," << N*N << "]: " ;
std::cin >> x ;
x = std::min( x, N*N ) ;
std::cout << "number of 1's == " << x << '\n' ;
// fill the first x positions with 1, rest remain as 0
std::fill_n( first, x, 1 ) ;
// randomly shuffle the elements around
std::shuffle( first, first+N*N, std::mt19937( std::random_device{}() ) ) ;
// print it out
for( constauto& row : mtx )
{
for( int v : row ) std::cout << v << ' ' ;
std::cout << '\n' ;
}
}