Why does my random number generator visit both arrays with the same numbers?

I use the method to create two new arrays intwith random numbers, but two arrays contain exactly the same numbers. Why is this happening?

    static void Main(string[] args)
    {
        int[] Foo1= Foo(1000);
        int[] Foo2= Foo(1000);
    }
    static int[] Foo(int length)
    {
        int[] Array = new int[length];
        Random r = new Random();
        for (int i = 0; i < length; i++)
        {          
            Array[i]=r.Next(1, 101);   
        }
        //Thread.Sleep(6);
        return Array;
    }
+3
source share
6 answers

You are not seeding Random , but you probably use it close enough between calls that the default seed is the same in both cases:

. , , . . , , (Int32) . . Random (Int32) .

+6

, , .

:

static void Main(string[] args)
{
    Random r = new Random();
    int[] Foo1= Foo(1000,r);
    int[] Foo2= Foo(1000,r);
}
static int[] Foo(int length, Random r)
{
    int[] Array = new int[length];

    for (int i = 0; i < length; i++)
    {          
        Array[i]=r.Next(1, 101);   
    }
    //Thread.Sleep(6);
    return Array;
}
+5

" Random " . Random. , , Random .

(, Random , ) - , .

+5

- Random, , -randoms. , Random , . , , . Random Main Foo, :

static void Main(string[] args)
{
    Random r = new Random();
    int[] Foo1= Foo(1000, r);
    int[] Foo2= Foo(1000, r);
}
static int[] Foo(int length, Random r)
{
    int[] Array = new int[length];
    for (int i = 0; i < length; i++)
    {          
        Array[i]=r.Next(1, 101);   
    }
    //Thread.Sleep(6);
    return Array;
}

: . , , .

+3

Random ,

  new Random(Guid.NewGuid().GetHashCode());
+3

Because you use almost the same seed. Try moving Random r = new Random();outside this method.

+1
source

Source: https://habr.com/ru/post/1791483/


All Articles