Fariz Luqman
Fariz Luqman

Reputation: 914

Select any random string from a list

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 :)

Upvotes: 2

Views: 21479

Answers (5)

christopher
christopher

Reputation: 27346

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 :)

Upvotes: 2

Sreenikethan I
Sreenikethan I

Reputation: 331

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

Upvotes: 1

SysDragon
SysDragon

Reputation: 9888

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

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460138

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

Upvotes: 11

cf_en
cf_en

Reputation: 1661

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

Upvotes: 1

Related Questions