Public Group

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

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

## 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 on other sites
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 on other sites
Facepalm!

That answer proves i'm still a noob . Thanks!

##### Share on other sites

Facepalm!

That answer proves i'm still a noob . Thanks!

Don't worry about it! It's all part of the learning process.

##### 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 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.

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

• 15
• 14
• 10
• 9
• 11
• ### Forum Statistics

• Total Topics
634096
• Total Posts
3015493
×