Jump to content
  • Advertisement
Sign in to follow this  
menyo

[C#] pick random from a set of numbers?

This topic is 2535 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi,

I was wondering what would be a easy way to pick randomly from a set of numbers.

random.Next(4,22,31,65,73) would not work...

My fix to this would be to pick them by percentages and use if statements or case switches to assign my specific numbers.

number = random.Next(1, 101);
if (number <= 20) numberPicked = 4;
else if (number <= 40) numberPicked = 22;
etc..

I'm wondering if there is a better way.

Share this post


Link to post
Share on other sites
Advertisement
Put the number into an array of ints.

Then generate the number between 0 to (Total numbers - 1)

And voila! :)



private int GetRandomNumber()
{
int number = Random.Next(0, 6) //Generates 0 to 5;
int[] choices = new int[5] { 4,22,31,65,73 };

return choices[number];
}


Do note, that, if you have a considerable amount of numbers, you could store it all in a file and then read it into an array.

There's also the List<int> approach, but that's just overkill?

Share this post


Link to post
Share on other sites
There are many ways to do it, each with their own merit. One is with a little generic extension method.


static class Util
{
static public T PickRandom ( this T[] Selection )
{
var rnd = new Random();
return selection[ rnd.Next( selection.Length ) ];
}
}

This adds an extra function to every type of array - you can use it in the following way:


int[] choices = new int[5] { 4,22,31,65,73 };
int MyNumber = choices.PickRandom();

Or you can make a generic method with a variable number of parameters, to pass your input in directly.


T PickRandom ( params T[] Selection )
{
var rnd = new Random();
return selection[ rnd.Next( selection.Length ) ];
}

to be used this way:


int MyNumber = PickRandom( 22, 31, 54, 123, 99 );

or

int[] choices = new int[5] { 4,22,31,65,73 };
int MyNumber = PickRandom( choices );

or

String MyString = PickRandom( "the", "quick", "brown", "fox" );

Share this post


Link to post
Share on other sites
You should make PickRandom as extension on Random class, not Array. Because you don't want to instantiate new Random object on every selection - you should give that choise to user.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!