Terrykk
Terrykk

Reputation: 169

Random in a loop problerm

Random r = new Random(DateTime.Now.Millisecond);

int numberOfFoos = foos.Count;
int fooIndex1 = 0,fooIndex2 = 0;

Foo foo1 = new Foo();
Foo foo2 = new Foo();

do
{
    while(fooIndex1 == fooIndex2)
    {
        fooIndex1 = r.Next(4);
        fooIndex2 = r.Next(4);
    }

    foo1 = foosList[fooIndex1];
    foo2 = foosList[fooIndex2];
}while(foo1.NumberOfLittleFoos == 0 || foo2.NumberOfLittleFoos == 0);

Why fooIndex1 is always 0 and fooIndex2 is always 2? I was trying to use Guid.NewGuid().GetHashCode() to generate random integers, but it still doesn't work rightly.

By this code I am trying to select 2 different Foo's from foosList.

I would be grateful for any help.

Upvotes: 0

Views: 25

Answers (1)

Nikita
Nikita

Reputation: 6427

Your code will return same values for fooIndex1 and fooIndex2 only if DateTime.Now.Millisecond is the same for different runs. It's specified in Random class specification. I've have run your code twice. First run gives fooIndex1 = 0, fooIndex2 = 2 and the second fooIndex1 = 1, fooIndex2 = 3.

Strange that you use r.Next(4). May be it's better to use r.Next(foosList.Count) to be able to access all items in your foosList.

Upvotes: 1

Related Questions