How to Choose Random number from given list of numbers in VB.Net

后端 未结 4 602
清酒与你
清酒与你 2021-01-29 03:35

I want to create a random number generator in VB.NET But from my own given list of numbers

Like Chose random numbers fro

相关标签:
4条回答
  • 2021-01-29 03:46

    Already built into .NET base of 'Random' and then extending that into your existing choices. This is NOT the same as generating the number from a Random as you are specifying YOUR OWN list first and then merely getting positioning with the help of a new Rand and using your length as a ceiling for it.

     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
    
    0 讨论(0)
  • 2021-01-29 03:46

    Here is the function you can try, see more here 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
    
    0 讨论(0)
  • 2021-01-29 03:47

    This is how you get a random natural number in the interval of [0, n - 1]:

    CInt(Rnd() * n)
    

    Let's suppose you have a List of n elements. This is how you get a random element from it:

    MyList(CInt(Rnd() * n))
    
    0 讨论(0)
  • 2021-01-29 03:47

    I would create a random number generator to generate a random number in the range of the list/array length, then use the result to point to the index of your number list.

    Dim numbers As Integer() = New Integer() {1,2,5,6,7,8,12,43,56,67}
    
    Dim randomKey = numbers(CInt(Rnd() * numbers.length))
    

    *Edited based on Lajos Arpad's answer of how to get the random number

    0 讨论(0)
提交回复
热议问题