简体   繁体   中英

How to choose a random element from an array in Visual Basic

I have created an array of Integer and want to choose a random element from it. How do I do that?

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)

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)

Rnd can get [0,1),then mutiple Your arraylength, you can get number between [0,YourArrayLength)

Randomize
Int(array.length* Rnd)

Visual Basic 6.0

Dim A() as string
chose = Int(Rnd * UBound(A)) 

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在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM