0

In one of my classes at school, part of my assignment includes creating a constructor that assigns random values into a 2D array. While I have been able to create the array, have the constructor assign random values into said array, I cannot seem to create multiple objects with different 2D arrays. Any object I make seems to hold the same values previously assigned to the first one. I am fairly new at c++ so I assume the answer is barely flying over my head. TIA

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

using namespace std;

const int sizeOfArray = 3;
int myArray;//a

class Matrix
{
public:
  int myArray[sizeOfArray][sizeOfArray];//a
  Matrix ()//b
  {
    srand(time(NULL));
    for(int i = 0; i < sizeOfArray; i++){
      for(int j = 0; j < sizeOfArray; j++){
      myArray[i][j] = rand() % 10;
      }
    }
  }

  void printMyArray();

};
void Matrix::printMyArray()//c
{
  cout<<"The Matrix is as follows: \n"<<endl;
  cout<<myArray[0][0]<<"\t"<<myArray[0][1]<<"\t"<<myArray[0][2]<<"\n"<<endl;
  cout<<myArray[1][0]<<"\t"<<myArray[1][1]<<"\t"<<myArray[1][2]<<"\n"<<endl;
  cout<<myArray[2][0]<<"\t"<<myArray[2][1]<<"\t"<<myArray[2][2]<<"\n"<<endl;
}

int main()
{
  Matrix matrix;
  matrix.printMyArray();

  Matrix natrix;
  natrix.printMyArray();

  return 0;
}

I want the output to spit out two different arrays, however, the same array is repeated twice with the output as:

The Matrix is as follows:

4 0 9

6 0 4

6 3 0

The Matrix is as follows:

4 0 9

6 0 4

6 3 0

cellifake
  • 25
  • 1
  • 5
  • Unrelated, but why is there a `int myArray;` in the global scope? – super Oct 21 '19 at 21:42
  • There are many random number generation options available to the C++ programmer these days than `rand`. Consider using [`std::uniform_int_distribution`](https://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution) instead. And if you want a few chuckles and [an explanation of why `rand` isn't all that good...](https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful) – user4581301 Oct 21 '19 at 21:54
  • There is no reason I just don't know how to code haha. I believe I put that there to test something a couple of days ago when I started this part of the assignment. Thanks for the catch though! – cellifake Oct 21 '19 at 22:09

1 Answers1

1

You are seeding the random number generator with the same value and so restarting the same sequence of numbers.

time() is only accurate down to the second, and your code is running a lot faster than that thus you get the same seed most of the time (in rare occasions it might be different).

To prove this, add a sleep(2) between the object creations - then you'll get a different seed for the RNG.

To solve it once and for all: don't seed the RNG in your class, do it once at the start of main()

John3136
  • 28,809
  • 4
  • 51
  • 69