问题
I want to create a random number generator in VB.NET But from my own given list of numbers
Like Chose random numbers from [1,2,3,4,5,6] e.t.c
回答1:
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))
回答2:
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
回答3:
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
回答4:
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
来源:https://stackoverflow.com/questions/41490639/how-to-choose-random-number-from-given-list-of-numbers-in-vb-net