I have a standard deck of 52 cards is represented in an array. Each card is represented as an integer. I wrote the below function to shuffle the cards. Does the code below look ok?
Module Module3
Sub Main()
' initialize array
Dim Cards(52) As Integer
' Unit Test
' Pass array as argument.
Console.WriteLine(shuffle(Cards))
End Sub
Function shuffle(ByVal Cards() As Integer)
Dim counter = 1
Dim rand = New Random()
For Each card In Cards
' Grab random number with range of 52
Dim n = rand.Next(52)
' Pick a card
Dim temp = Cards(counter)
' Swap picked card with random card
Cards(counter) = Cards(n)
Cards(n) = temp
counter += 1
Next
Return (Cards)
End Function
End Module
No, the code doesn’t do what you say.
This will create an array for 53 cards, not 52. Use:
When shuffling, swap each card with a card earlier in the deck (or itself), not anywhere in the deck. (This is the principle of the Fisher-Yates shuffle.)
Instead of having a counter separate from the loop, use the counter for the looping.