如何从VB.Net中给定的数字列表中选择随机数

时间:2017-01-05 17:01:39

标签: vb.net vb.net-2010

我想在我自己给定的数字列表中用VB.NET 创建一个随机数生成器

  

喜欢从[1,2,3,4,5,6] e.t.c选择随机数

4 个答案:

答案 0 :(得分:2)

这是在[0,n - 1]区间内获得随机自然数的方法:

sed -r -e 's///g'

假设您有CInt(Rnd() * n) List元素。这就是你从中得到随机元素的方法:

n

答案 1 :(得分:1)

我会创建一个随机数生成器来生成列表/数组长度范围内的随机数,然后使用结果指向数字列表的索引。

Dim numbers As Integer() = New Integer() {1,2,5,6,7,8,12,43,56,67}

Dim randomKey = numbers(CInt(Rnd() * numbers.length))

*已编辑基于Lajos Arpad关于如何获取随机数的答案

答案 2 :(得分:1)

已经内置于' Random'的.NET基础然后将其扩展到您现有的选择中。这与从Random生成数字不同,因为您首先指定您自己的列表,然后仅在新Rand的帮助下获取定位并使用您的长度作为它的上限。

 Sub Main()
    'Say you have four items in your list
    Dim ls = New List(Of Integer)({1, 4, 8, 20})
    'I can find the 'position' of where the count of my array could be
    Dim rand = New Random().Next(0, ls.Count)
    'This will give a different 'position' every time.
    Console.WriteLine(ls(rand))

    Console.ReadLine()
  End Sub

答案 3 :(得分:0)

以下是您可以尝试的功能,请点击此处Random integer in VB.NET

Public Function GetRandom(ByVal Min As Integer, ByVal Max As Integer) As    Integer
Dim Generator As System.Random = New System.Random()
Return Generator.Next(Min, Max + 1)
End Function