# RANDOM NUMBER GENERATION

How can I generate a random matrix of order m by n using rand() in C++ with a specified range?

rand() is only a pseudo random number generator (PRNG) and not true random - this isn’t a problem in a lot of applications but IMO you should get in the habit of thinking about it.

anyway to seed the PRNG so that it comes up with a different sequence each time you run the program the following is a commonly used approach…

``````    #include <time.h>
:
:
srand(time(NULL)); //seeds the prng. just do it once - maybe at the start of main()
:
:
x=rand();
y=rand(); //etc etc``````

You want something like this?

``````#include <cstdio>
#include <cstdlib>
#include <ctime>
const int MAX_N = 100;

// returns a random number x, where a <= x <= b
// srand(time(NULL)) must be called before using this function
int random(int a, int b){
return (rand() % (b - a + 1)) + a;
}
int main() {
srand(time(NULL)); // initalizing PRNG
int n = 5;
int m = 5;
int a[MAX_N][MAX_N];
// assign each number of the matrix with a random number between 1 and 100
for(int i = 0; i < n; i ++){
for(int j = 0; j < m; j++){
a[i][j] = random(1, 100);
}
}
// print the matrix for visualisation
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
printf("%d ", a[i][j]);
}
printf("\n");
}
return 0;
}
``````

#include “iostream”
#include “algorithm”
#include “vector”
#include “cstdlib”

using std::vector;

class rand_range { // functor for generating random values in range
public:
rand_range(int _min_val, int _max_val) : min_val(_min_val), max_val(_max_val) { }
int operator()() { return min_val + rand() % (max_val - min_val + 1); }
private:
int min_val;
int max_val;
};

int main()
{
const int m = 10; // 10 rows
const int n = 20; // 20 cols
const int r_min = 100; // random range min
const int r_max = 200; // random tange max

``````vector<int> v_row(n);               // allocate matrix
vector<vector<int> > v_matrix(m, v_row);

for (auto &v_row : v_matrix)        // init matrix with random values
{
std::generate(v_row.begin(), v_row.end(), rand_range(r_min, r_max));
}

for (auto const &v_row : v_matrix)  // display contents of matrix
{
for (auto const i : v_row)
{
std::cout << " " << i;
}
std::cout << std::endl;
}

return 0;
``````

}