简体   繁体   English

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

[英]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.0Len-1范围内生成一个随机整数,其中Len是数组的长度。 To make a random integer, use an instance of the Random class.要生成随机整数,请使用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)

Rnd can get [0,1),then mutiple Your arraylength, you can get number between [0,YourArrayLength) Rnd 可以得到[0,1),那么multiple你的arraylength,你可以得到[0,YourArrayLength)之间的数

Randomize
Int(array.length* Rnd)

Visual Basic 6.0 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.因此,例如,如果您不想在 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.

I also tried.我也试过了。 I tried to select one out of 3 elements and notice that only the first 2 elements get chosen.我试图从 3 个元素中选择一个,并注意到只有前 2 个元素被选中。 The third element is never chosen永远不会选择第三个元素在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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