-1

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.

  • its gets the same "seed" move the random to main before the for loop [Random.Next returns always the same values](https://stackoverflow.com/questions/1654887/random-next-returns-always-the-same-values) – styx Jul 04 '22 at 05:13
  • this answers your question: [Random.Next returns always the same values](https://stackoverflow.com/questions/1654887/random-next-returns-always-the-same-values) – Ňɏssa Pøngjǣrdenlarp Jul 04 '22 at 05:15

1 Answers1

3

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.

Amadan
  • 191,408
  • 23
  • 240
  • 301