15,946,179 members
4.00/5 (1 vote)
See more:
Hi
I have a enum which consists of four elements (Up, Down, Left, Right).
I want to select randomly an element.
Th current problem is that most of the applications run gives me Up/Down.
How do I give a 25% probability for each element?

My code is simple:
C#
```Random rnd = new Random(DateTime.Now.Millisecond);
int randomGenerated = 0;
for (int index = 0; index < 20; index++)
{
randomGenerated = rnd.Next(1, 301) / 100;
Move((Directions)randomGenerated);
}```

As you can see I tried to generate between 1 and 301 to give better chances for each element to be selected but it didn't help.

Thanks
Shahar
Posted

## Solution 1

Don't. Just do this:
C#
```Random rnd = new Random();
int randomGenerated = 0;
for (int index = 0; index < 20; index++)
{
randomGenerated = rnd.Next(4);
Move((Directions)randomGenerated);
}```

Random numbers are just that. By restricting your number space to 0-300 and then dividing by a hundred , you are reducing the chances of getting a random distribution:
```0 : 100 chances in 301
1 : 100 chances in 301
2 : 100 chances in 301
3 :   1 chance  in 301```

Typo: "ten" for "a hundred" - OriginalGriff[/edit]

v2

## Solution 2

C#
```enum Direction
{
Up = 0, Down, Left, Right
}

static Direction GetRandomDirection(Random random)
{
return (Direction)random.Next((int)Direction.Up, (int)Direction.Right + 1);
}```

This works fine for me.

As Random is normally distributed, P(Up) = P(Down) = P(Left) = P(Right) = 1/4 = 25%.