Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,895 questions

51,826 answers

573 users

How to fill a matrix with 1 and 0 in random locations with C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>

#define ROWS 5
#define COLS 4

void fillMatrixWithRandom0and1(std::vector<std::vector<int>>& matrix, int rows, int cols) {
    // Seed the random number generator
    std::srand(std::time(0));

    // Resize the matrix to the desired dimensions
    matrix.resize(rows, std::vector<int>(cols));

    // Fill the matrix with random 0s and 1s
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            matrix[i][j] = std::rand() % 2; // Generates either 0 or 1
        }
    }
}

int main() {
    std::vector<std::vector<int>> matrix;

    fillMatrixWithRandom0and1(matrix, ROWS, COLS);

    // Print the matrix
    for (const auto& row : matrix) {
        for (int val : row) {
            std::cout << val << " ";
        }
        std::cout << std::endl;
    }
}


 
/*
run:

1 1 1 0 
0 0 0 0 
0 1 0 0 
0 1 1 1 
0 0 1 0
  
*/

 



answered Jan 24, 2025 by avibootz

Related questions

1 answer 59 views
1 answer 83 views
1 answer 79 views
1 answer 66 views
1 answer 71 views
1 answer 64 views
...