Random number Selector

anybloodyid

Member
Joined
Jan 25, 2018
Messages
16
Programming Experience
Beginner
Hi and thanks for looking,
I have a button that selects a random number from 30 numbers how do I make sure the same number is not picked again.
My thoughts,
Randomise a List box then remove the number that's picked before repeating.
Or an array, same idea remove number after it has been randomly chosen.
Or is there another way?
 
There's no need to use a ListBox unless you want to display the numbers to the user. A ListBox is a control so only use it if you need a control. If you just need to store values, use a collection, which is exactly what a ListBox stores its items in.
 
There are three ways to approach this:
  1. After using a random number, store it in a collection. The next time you generate a number, check that list to see if it is already there and, if so, try again. Keep doing this until you don't find a match.
  2. Create a list of all possible values, select one by index at random and remove it from the list.
  3. Create a list of all possible values and shuffle it, then take the numbers in order one by one.
For a large number of possible values from which you only want to generate a few selections, the first option is probably better. For a small number of possible from which you want to use some or all, the last two options are better. For scenarios somewhere in the middle, you may want to test each option and compare performance.

I'll leave the first two to you if you want to implement them but here's an implementation of the third option:
VB.NET:
Dim rng As New Random

For Each n In Enumerable.Range(1, 30).OrderBy(Function(i) rng.NextDouble())
    Console.WriteLine(n)
Next
 
Thanks John,
Long time since I was last here will look at the second option 'Create a list of all possible values, select one by index at random and remove it from the list.'
 
In that case, you would populate a List(Of Integer) and then use the Count of that as the upper limit when calling Random.Next. The random number will then be an index into the list and you can call RemoveAt to remove the item at that index once you've got it.
 

Latest posts

Back
Top