Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why Random range give same output value every time?

Here is the code which i used to for implementing Random class

class Program
{
    public static void Main()
    {
        for (int j = 0; j < 5; j++)
        { 
            foreach (var item in GenerateRandomList(new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }))
                Console.Write(item + " ");
            Console.WriteLine(" ");
        }

    }
    public static List<int> GenerateRandomList(List<int> arr)
    {
        var random = new Random(new Random().Next(1,10000));
        var ls = new List<int>();
        while(arr.Count>0)
        {
            var index = random.Next(0, arr.Count-1);
            ls.Add(arr[index]);
            arr.RemoveAt(index);
        }
        return ls;
    }
}

below are the results I am getting

first time
4 3 8 2 1 6 7 5 9 0
4 3 8 2 1 6 7 5 9 0
4 3 8 2 1 6 7 5 9 0
4 3 8 2 1 6 7 5 9 0
4 3 8 2 1 6 7 5 9 0

second time
6 3 4 2 8 5 9 1 7 0
6 3 4 2 8 5 9 1 7 0
6 3 4 2 8 5 9 1 7 0
6 3 4 2 8 5 9 1 7 0
6 3 4 2 8 5 9 1 7 0

third time 
9 2 4 8 1 6 3 5 7 0
9 2 4 8 1 6 3 5 7 0
9 2 4 8 1 6 3 5 7 0
9 2 4 8 1 6 3 5 7 0
7 1 3 6 5 2 8 9 4 0

and So on..

what am i Missing?
sometimes it give different result but again it starts to repeat previous result.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

new Random() creates a new random number generator instance, with the default seed.

In .NET Framework, the default seed value is time-dependent. In .NET Core, the default seed value is produced by the thread-static, pseudo-random number generator. From docs:

If the same seed is used for separate Random objects, they will generate the same series of random numbers.

If the default seed is time-based, and you create five Random objects in a quick succession, each of your generators will get the same seed (since time is not as precise that each instruction executes on a different timestamp), and thus produce the same pseudorandom number sequence.

You will want to create a Random instance only once; for example, as a class field.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading