Click here to Skip to main content
15,949,686 members
Please Sign up or sign in to vote.
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

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


[edit]Typo: "ten" for "a hundred" - OriginalGriff[/edit]
 
Share this answer
 
v2
I didn't understand your problem...

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%.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900