Reputation: 8976
I have created an array of Integer and want to choose a random element from it. How do I do that?
Upvotes: 1
Views: 33303
Reputation: 33050
Just want to say that the accepted answer is incorrect.
This is the correct one
Dim Rand as New Random()
Dim Index as Integer = Rand.Next(0, YourArray.Length)
Dim SelectedValue = YourArray(Index)
Why?
Because the maximum value is exclusive. So if you won't to pick among 3 elements, for example, the maximum value should be 3, not 2.
'
' Summary:
' Returns a non-negative random integer.
'
' Returns:
' A 32-bit signed integer that is greater than or equal to 0 and less than System.Int32.MaxValue.
Public Overridable Function [Next]() As Integer
'
' Summary:
' Returns a random integer that is within a specified range.
'
' Parameters:
' minValue:
' The inclusive lower bound of the random number returned.
'
' maxValue:
' The **exclusive** upper bound of the random number returned. maxValue must be greater
' than or equal to minValue.
'
' Returns:
' A 32-bit signed integer greater than or equal to minValue and **less than** maxValue;
' that is, the range of return values includes minValue but not maxValue. If minValue
' equals maxValue, minValue is returned.
'
' Exceptions:
' T:System.ArgumentOutOfRangeException:
' minValue is greater than maxValue.
I also tried. I tried to select one out of 3 elements and notice that only the first 2 elements get chosen. The third element is never chosen
Upvotes: 0
Reputation: 460
YourArray(New Random().Next(0,YourArray.Length-1))
Or separated out for more clarity:
Dim Rand as New Random()
Dim Index as Integer = Rand.Next(0, YourArray.Length - 1)
Dim SelectedValue = YourArray(Index)
Upvotes: 7
Reputation: 172
Rnd can get [0,1),then mutiple Your arraylength, you can get number between [0,YourArrayLength)
Randomize
Int(array.length* Rnd)
Upvotes: 1
Reputation: 726479
Make a random integer number in the range from 0
to Len-1
, where Len
is the length of your array. To make a random integer, use an instance of the Random
class.
DIM rand As New Random
DIM idx as rand.Next(0, Len)
REM Now you can pick an element idx from the array
REM to get a random element.
DIM res as myArray(index)
Upvotes: 1