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
Answer is not clear.
And please assume me a beginner.
you can write values to fill an m by n array using a loop that iterates n times inside a loop that iterates m times
you could limit the range of values using % and + e.g if you want a number x where 1<=x<=10 you could do
x=rand()%10+1;
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;
}
There are still standard library and prototype issues.
answer below from @gdisastery1 compiles & runs perfectly on g++ 4.5.3 here
as an experiment you could comment out srand(time(NULL)); and see the difference it makes to the output over repeated runs.
#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;
}