【问题标题】:How to choose a random element from an array in Visual Basic如何在 Visual Basic 中从数组中选择一个随机元素
【发布时间】:2012-12-27 22:19:55
【问题描述】:

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

【问题讨论】:

标签: arrays visual-studio-2008 vba random


【解决方案1】:
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)

【讨论】:

  • Random 类的一个实例有一个名为“Next”的函数,该函数将最小值和最大值作为随机数的范围,在这种情况下,范围是 0 到数组长度减一。然后将该数字用作数组的索引,选择那里的任何元素。我把它放在一行中,但为了清楚起见,你可以把它分开。我会更新一个例子。
  • 非常感谢。这会有所帮助。
【解决方案2】:

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)

【讨论】:

    【解决方案3】:

    Rnd可以得到[0,1),然后再乘以你的arraylength,你可以得到[0,YourArrayLength)之间的数

    Randomize
    Int(array.length* Rnd)
    

    【讨论】:

      【解决方案4】:

      只想说接受的答案不正确。

      这是正确的

      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 个元素被选中。永远不会选择第三个元素

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-07-23
        • 2011-06-30
        • 1970-01-01
        • 1970-01-01
        • 2017-05-01
        • 1970-01-01
        相关资源
        最近更新 更多