Solved

# vb.net - get random from array

Posted on 2013-05-14
435 Views
Hello,
I am trying to get 3 results when I call showRand() function.
how can I make something so that I dont get the same number twice?

``````        Dim numbs() As String = {"1", "2", "3", "11", "12", "13"}
Debug.Print(showRand(numbs, 3))

Function showRand(ByRef data() As String, Optional ByVal MoreThanOne As Integer = 0) As String
Dim Result As String = Nothing
Dim Rand As New Random

If MoreThanOne > 0 Then
For i = 1 To MoreThanOne
Result += data(Rand.Next(0, data.GetUpperBound(0) + 1)) & ","
Next
Result = Result.Substring(0, Result.Length - 1)
Else
Result = data(Rand.Next(0, data.GetUpperBound(0) + 1))
End If

Return Result
End Function
``````
0
Question by:XK8ER
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
1 Comment

LVL 86

Accepted Solution

Mike Tomlinson earned 500 total points
ID: 39167123
One way...
``````    Function showRand(ByVal data() As String, Optional ByVal MoreThanOne As Integer = 0) As String
Dim Result As String = Nothing
Static Rand As New Random

If MoreThanOne > 0 Then
If MoreThanOne <= data.Length Then
Dim index As Integer
Dim strings As New List(Of String)(data)
Dim selected As New List(Of String)
For i As Integer = 1 To MoreThanOne
index = Rand.Next(0, strings.Count)
strings.RemoveAt(index)
Next
Result = String.Join(",", selected.ToArray)
End If
Else
Result = data(Rand.Next(0, data.Length))
End If

Return Result
End Function
``````
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

### Suggested Solutions

Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
Introduction to Processes
Finding and deleting duplicate (picture) files can be a time consuming task. My wife and I, our three kids and their families all share one dilemma: Managing our pictures. Between desktops, laptops, phones, tablets, and cameras; over the last decade…
###### Suggested Courses
Course of the Month8 days, 7 hours left to enroll