Random binary numbers matrix

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)
Thank you so much!!!
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++)

and I want to add an x number of 1's
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
   const int N = 3;
   int M[N][N] = {};
   srand( time( 0 ) );
   
   int x;
   cout << "Input x: ";   cin >> x;
   if ( x > N * N ) 
   {
      cout << "Impossible!\n";
      return 1;
   }

   int filled = 0;
   while ( filled < x )
   {
      int *p = M[0] + rand() % ( N * N );
      if ( *p == 0 )
      {
         *p = 1;
         filled++;
      }
   }
   for ( int i = 0; i < N; i++)
   {
      for ( int j = 0; j < N; j++ ) cout << M[i][j] << '\t';
      cout << '\n';
   }
}
This is one way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#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( const auto& row : mtx )
    {
        for( int v : row ) std::cout << v << ' ' ;
        std::cout << '\n' ;
    }
}

http://coliru.stacked-crooked.com/a/4462282581a4bcc3
THANKS!!!!
Topic archived. No new replies allowed.