adding in random numbers

How would I go about adding in random numbers (1s and 0s) instead of prompting the user for every single number within the matrix.

#include <iostream>
#include <ctime>
#include <cmath>
#include <cstdlib>

using namespace std;

int main()
{
srand(time(0));
//initialize the matrix
int** Matrix; //A pointer to pointers to an int.
int rows,columns;
cout<<"Enter number of rows: ";
cin>>rows;
cout<<"Enter number of columns: ";
cin>>columns;
Matrix=new int*[rows]; //Matrix is now a pointer to an array of 'rows' pointers.

//define the matrix
for(int i=0;i<rows;i++)
{
Matrix[i]=new int[columns]; //the ith array is initialized
for(int j= 0;j<columns;j++) //the i,jth element is defined


{
cout<<"Enter element in row "<<(i+1)<<" and column "<<(j+1)<<": ";
cin>>Matrix[i][j];
}
}

//Print the matrix
cout<<"The matrix you have input is:\n";
for(int i=0;i<rows;i++)
{
for(int j=0;j<columns;j++)
cout<<Matrix[i][j]<<"\t"; //tab between each element
cout<<"\n"; //new row
}

//now, we have to free up the memory we took by releasing each vector:
for(int i=0;i<rows;i++)
delete[] Matrix[i];
}
Last edited on
Tell me if I am understanding this correctly. This example shows how to add in a "random" number a certain percentage of the time. I was looking at using rand()%2 however my issue is where I can put it. I believe this will create a Matrix looking effect like from the movie.
Why have you posted two threads with basically same question? http://www.cplusplus.com/forum/beginner/237020/
That is double-posting.

JLBorges wrote in the other thread:
1
2
3
4
5
6
7
8
9
    // fill the matrix with random integers uniformly distributed in [20,70]
    // http://en.cppreference.com/w/cpp/numeric/random
    std::mt19937 rng( std::random_device{}() ) ;

    std::uniform_int_distribution<int> distrib(20,70) ;
    // http://www.stroustrup.com/C++11FAQ.html#for
    // http://www.stroustrup.com/C++11FAQ.html#auto
    for( auto& row : matrix ) // for each row in the matrix
        for( int& v : row ) v = distrib(rng) ; // assign a random value to each int 

The same with bernoulli:
1
2
3
4
5
6
7
8
9
10
11
12
    // fill the matrix with random integers uniformly distributed in [0,1]
    // https://kristerw.blogspot.fi/2017/05/seeding-stdmt19937-random-number-engine.html
    std::random_device rd;
    std::array<int, std::mt19937::state_size> seed_data;
    std::generate_n( seed_data.data(), seed_data.size(), std::ref(rd) );
    std::seed_seq seq( std::begin(seed_data), std::end(seed_data) );
    std::mt19937 rng( seq );

    std::bernoulli_distribution distrib( 0.5 ) ; // 50/50 chances

    for( auto& row : matrix )
        for( int& v : row ) v = ( distrib(rng) ) ? 1 : 0 ;
Topic archived. No new replies allowed.