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 Number Generator

Status
Not open for further replies.

LordofShadows

Programmer
Apr 22, 2002
13
US
I am writing a program that simulates the card game "War". I have most of it written, but I am stuck at "shuffling" the cards. I've already created an array that has all 52 cards, and I have an array set up to take in those cards randomly. Here's my problem: I'm using a For...Next loop with an Rnd statement inside it:
For x = 0 To 51
Randomize Timer
y = Int(51 * Rnd)
ShufCardArray(x, 0) = CStr(CardArray(y, 0))
ShufCardArray(x, 1) = CStr(CardArray(y, 1))
Next x
The only part that is not working is that "y" isn't always a different value. Is there any way I can prevent "y" from receiving the same random value?
 
Do a check on y's value to see if it's been used. Craig, mailto:sander@cogeco.ca

Remember not to name the Lambs...
It only makes the chops harder to swallow
 
This should work. Try it out.
[tt]
Dim usedNumbers(52) as integer
Dim z as Integer

For x = 0 To 51
Randomize Timer
:GetADifferentCard
y = Int(51 * Rnd)
For z = 0 to x
If y = UsedNumbers(z) then
GoTo GetADifferentCard
End If
Next z
ShufCardArray(x, 0) = CStr(CardArray(y, 0))
ShufCardArray(x, 1) = CStr(CardArray(y, 1))
UsedNumbers(x) = y
Next x
[/tt] Craig, mailto:sander@cogeco.ca

Remember not to name the Lambs...
It only makes the chops harder to swallow
 
Yes, do this.

Add the different cards in a collection rather than an array. Loop based on the max amount of cards in the collections and randomly pulling out a card based on the count in the collection. Once that card is stored in your new, seperate collection, remove the item in the first collection, randomly pull again based on the new count.

Here is an example :


Private Sub cmdShuffle_Click()
Dim oCol1 As New Collection
Dim oCol2 As New Collection
Dim i As Integer
Dim iThis As Integer
Dim sMsg As String

initCards oCol1
Randomize
Do Until (oCol1.Count = 0)
iThis = Int((oCol1.Count * Rnd) + 1)
oCol2.Add oCol1(iThis), oCol1(iThis)
oCol1.Remove (iThis)
Loop

sMsg = ""
For i = 1 To oCol2.Count
sMsg = sMsg & oCol2(i) & vbNewLine
Next i
MsgBox sMsg
End Sub

Private Sub initCards(ByRef oCol As Collection)
Dim i As Integer
Dim sCard As String
For i = 1 To 52
sCard = "Card" & CStr(i)
oCol.Add sCard, sCard
Next i
End Sub

--

I just threw this together so it may not fit into your existing app perfectly but I know it does do the job.

I hope this is helpful (hint).
-Matt
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top