Home c++ Class - a matrix with random values ​​

Class – a matrix with random values ​​

Author

Date

Category

The goal is to create a matrix class that would be able to create two-dimensional arrays of given sizes, but with random values.
The array is created, but I get the same values ​​every time. Please tell me what the problem is?

# include & lt; iostream & gt;
#include & lt; time.h & gt;
#include & lt; iomanip & gt;
using namespace std;
class Matrix
{
private:
int str;
int col;
int ** mat;
public:
Matrix (int str, int col) // class constructor
{
  this - & gt; str = str;
  this - & gt; col = col;
  mat = new int * [str];
  for (int i = 0; i & lt; str; i ++)
  {
    mat [i] = new int [col];
  }
  cout & lt; & lt; "Constructor" & lt; & lt; this & lt; & lt; endl;
}
void FillMatrix () // fill method
{
  srand (time (NULL));
  for (int i = 0; i & lt; str; i ++)
  {
    for (int j = 0; j & lt; col; j ++)
    {
      mat [i] [j] = rand ()% 10;
    }
  }
}
void PrintMatrix () // output
{
  for (int i = 0; i & lt; str; i ++)
  {
    for (int j = 0; j & lt; col; j ++)
    {
      cout & lt; & lt; setw (4) & lt; & lt; mat [i] [j];
    }
    cout & lt; & lt; endl;
  }
  cout & lt; & lt; endl;
}
~ Matrix () // destructor, I have to add it.
{
delete [] mat;
    cout & lt; & lt; "Destruct" & lt; & lt; this & lt; & lt; endl & lt; & lt; endl;
}
};
int main ()
{
setlocale (LC_ALL, "ru");
Matrix a (3, 3);
Matrix b (3, 3);
b.FillMatrix ();
a.FillMatrix ();
a.PrintMatrix ();
b.PrintMatrix ();
}

Answer 1

From here :

For any other value passed through the seed parameter, and
used when calling the srand function, the generation algorithm
pseudo-random numbers can generate different numbers with each
a subsequent call to the rand function. If you use the same
the seed value, with each call to the rand function, the generation algorithm
pseudo-random numbers will generate the same
sequence of numbers.

I would do this:

# include & lt; random & gt;
class Matrix
{
private:
  std :: mt19937 random_generator_;
  std :: uniform_int_distribution & lt; std :: uint8_t & gt; rand_uid (0, 9);
public:
  Matrix () // class constructor
  {
    std :: random_device random_device;
    random_generator_.seed (random_device ());
  }
  void FillMatrix () // fill method
  {
    for (int i = 0; i & lt; str; i ++)
    {
      for (int j = 0; j & lt; col; j ++)
      {
        mat [i] [j] = rand_uid (random_generator_));
      }
    }
  }
};

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions