Select any random string from a list

怎甘沉沦 提交于 2019-12-24 02:23:38

问题


How can I select any random string from a given list of strings? Example:

List1: banana, apple, pineapple, mango, dragon-fruit
List2: 10.2.0.212, 10.4.0.221, 10.2.0.223

When I call some function like randomize(List1) = somevar then it will just take any string from that particular list. The result in somevar will be totally random. How can it be done? Thank you very much :)


回答1:


Use Random

Dim rnd = new Random()
Dim randomFruit = List1(rnd.Next(0, List1.Count))

Note that you have to reuse the random instance if you want to execute this code in a loop. Otherwise the values would be repeating since random is initialized with the current timestamp.

So this works:

Dim rnd = new Random()
For i As Int32 = 1 To 10
    Dim randomFruit = List1(rnd.Next(0, List1.Count))
    Console.WriteLine(randomFruit)
Next

since always the same random instance is used.

But this won't work:

For i As Int32 = 1 To 10
    Dim rnd = new Random()
    Dim randomFruit = List1(rnd.Next(0, List1.Count))
    Console.WriteLine(randomFruit)
Next



回答2:


Create a List of Strings.
Create a random number generator: Random class
Call Random number generator's NextInt() method with List.Count as the upper bound.
Return List[NextInt(List.count)].
Job done :)




回答3:


Generate a random number between 1 and the size of the list, and use that as an index?




回答4:


Try this:

Public Function randomize(ByVal lst As ICollection) As Object
    Dim rdm As New Random()
    Dim auxLst As New List(Of Object)(lst)
    Return auxLst(rdm.Next(0, lst.Count))
End Function

Or just for string lists:

Public Function randomize(ByVal lst As ICollection(Of String)) As String
    Dim rdm As New Random()
    Dim auxLst As New List(Of String)(lst)
    Return auxLst(rdm.Next(0, lst.Count))
End Function



回答5:


You could try this, this is a simple loop to pick every item from a list, but in a random manner:

Dim Rand As New Random
For C = 0 to LIST.Count - 1 'Replace LIST with the collection name
    Dim RandomItem As STRING = LIST(Rand.Next(0, LIST.Count - 1)) 'Change the item type if needed (STRING)

    '' YOUR CODE HERE TO USE THE VARIABLE NewItem ''

Next


来源:https://stackoverflow.com/questions/15069736/select-any-random-string-from-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!