Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Random name problem

Status
Not open for further replies.

Mtlca401

Programmer
Mar 18, 2003
42
US
I have an array with 12 names already specified in it and I am trying to pull out 5 random names from that array(kinda like pulling names out of a hat), but the code I have duplicates the names. I don't know how to fix it.

Code:
Public strName As Variant
Public arrayName() As String

Public Function PlayerNames() As Integer
Dim intRnd As Integer, i As Integer

strName = Array("Craig", "Derek", "Jeff", "Piggy", "Erin", "Bourge", "Kristen", _
                "Mindy", "Gook", "Brett", "Jamie", "Peter")

ReDim arrayName(1 To 5) As String

For i = 1 To 5

Randomize

intRnd = Int((5 - 1)* Rnd) + 1

arrayName(i) = strName(intRnd)
Next i

End Function


Can anyone help? because I do not know anything about random generators.

Thanks
 
You need to modify the code like this.
___
[tt]
Public strName As Variant
Dim arrayName() As String

Public Function PlayerNames() As Integer
Dim intRnd As Integer, i As Integer, j As Integer, Idx() As Integer
Randomize
strName = Array("Craig", "Derek", "Jeff", "Piggy", "Erin", "Bourge", "Kristen", "Mindy", "Gook", "Brett", "Jamie", "Peter")
ReDim Idx(11) As Integer
For i = 0 To 11
Idx(i) = i
Next
For i = 0 To 11
intRnd = Int(Rnd * 12)
j = Idx(intRnd)
Idx(intRnd) = Idx(i)
Idx(i) = j
Next
ReDim arrayName(1 To 5) As String
For i = 1 To 5
arrayName(i) = strName(Idx(i))
Next i
End Function[/tt]
___

See also thread222-813668 about random number selection.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top