2

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

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
Fariz Luqman
  • 894
  • 5
  • 16
  • 27

5 Answers5

10

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
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • Much thanks, you're a live saver! This is my code: Dim rnd = New Random() Dim availServers(0 To 2) As String availServers(0) = "Deftones" availServers(1) = "Tool" availServers(2) = "Disturbed". Thank you :D – Fariz Luqman Feb 25 '13 at 15:03
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 :)

Sreenikethan I
  • 319
  • 5
  • 17
christopher
  • 26,815
  • 5
  • 55
  • 89
1

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

cf_en
  • 1,661
  • 1
  • 10
  • 18
1

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
SysDragon
  • 9,692
  • 15
  • 60
  • 89
1

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
Sreenikethan I
  • 319
  • 5
  • 17