C# random numbers

Question:

Why, when executing this code, all elements of the Jarr array have the same length,

static void Main(string[] args)
        {
            int[][] Jarr = new int[10][];
            for (int i = 0; i < Jarr.Length; i++)
            {
                Jarr[i] = new int[new Random().Next(10)];
            }
            for (int i = 0; i < Jarr.Length; i++)
            {
                for (int j = 0; j < Jarr[i].Length; j++)
                {
                    Console.Write("{0} ",Jarr[i][j]);
                }
                Console.WriteLine();
            }
        }

and when doing this is different?

static void Main(string[] args)
        {
            int[][] Jarr = new int[10][];
            Random rand = new Random();
            for (int i = 0; i < Jarr.Length; i++)
            {
                Jarr[i] = new int[rand.Next(10)];
            }
            for (int i = 0; i < Jarr.Length; i++)
            {
                for (int j = 0; j < Jarr[i].Length; j++)
                {
                    Console.Write("{0} ",Jarr[i][j]);
                }
                Console.WriteLine();
            }
        }
    }

Answer:

In the first case, you create a new instance of Random on each iteration, which is initialized with the system time. The system clock does not have time to update its value during the execution of the loop, so all Random instances are initialized with the same initial value – this is what is returned. In other words, each time the first value of the same pseudo-random sequence is chosen.

In the second case, you use one instance of Random and generate a sequence of pseudo-random numbers in which each number occurs equally likely (almost).

From MSDN :

The default seed value is derived from the system clock and has finite resolution. As a result, different Random objects that are created in close succession by a call to the default constructor will have identical default seed values ​​and, therefore, will produce identical sets of random numbers.

Scroll to Top