0

I am writing a program to create a matrix that will be filled with 1's and 0's.

var matrix = new int[3,3];

for (int i = 0; i < matrix.GetLength(0); i++)
{
    for (int j = 0; j < matrix.GetLength(1); j++)
    {
        var random = new Random();
        int rand = random.Next(0,2);
        matrix[i, j] = rand;
    }
}
for (int i = 0; i < matrix.GetLength(0); i++)
{
    for (int j = 0; j < matrix.GetLength(1); j++)
    {
        Console.Write(matrix[i, j] + " ");
    }
    Console.WriteLine();
}

The program always returns a matrix filled with 1's. I want it to be random i-e that contains 1's and 0's. What can be the problem?

Christos
  • 53,228
  • 8
  • 76
  • 108
Jamal Hussain
  • 391
  • 1
  • 3
  • 13

1 Answers1

3

Just move this line of code

var random = new Random();

before this line of code:

for (int i = 0; i < matrix.GetLength(0); i++)

That will solve your problem. Please have a look here.

Why this happens?

As it is stated here,

Every time you do new Random() it is initialized using the clock. This means that in a tight loop you get the same value lots of times. You should keep a single Random instance and keep using Next on the same instance.

Community
  • 1
  • 1
Christos
  • 53,228
  • 8
  • 76
  • 108