如何从Visual Basic中的数组中选择一个随机元素

时间:2013-01-14 01:26:04

标签: arrays visual-studio-2008 vba random

我创建了一个Integer数组,并希望从中选择一个随机元素。我该怎么做?

5 个答案:

答案 0 :(得分:4)

YourArray(New Random().Next(0,YourArray.Length-1))

或者为了更清晰而分开:

Dim Rand as New Random()
Dim Index as Integer = Rand.Next(0, YourArray.Length - 1)

Dim SelectedValue = YourArray(Index)

答案 1 :(得分:1)

0Len-1的范围内创建一个随机整数,其中Len是数组的长度。要创建随机整数,请使用Random类的实例。

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)

答案 2 :(得分:1)

Rnd可以获得[0,1],然后多次你的arraylength,你可以获得[0,YourArrayLength]之间的数字

Randomize
Int(array.length* Rnd)

答案 3 :(得分:0)

Visual Basic 6.0

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

答案 4 :(得分:0)

只想说接受的答案是错误的。

这是正确的

Dim Rand as New Random()
Dim Index as Integer = Rand.Next(0, YourArray.Length)

Dim SelectedValue = YourArray(Index)

为什么?

因为最大值是独占的。因此,例如,如果您不想在 3 个元素中进行选择,则最大值应该是 3,而不是 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.

我也试过了。我试图从 3 个元素中选择一个,并注意到只有前 2 个元素被选中。永远不会选择第三个元素 enter image description here