Bruno Bruno - 9 months ago 55 Question

Write a method to shuffle a deck of cards in VB.NET

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.

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


Return (Cards)

End Function

End Module

Answer Source

No, the code doesn't do what you say.

Dim Cards(52) As Integer

This will create an array for 53 cards, not 52. Use:

Dim Cards(51) As Integer

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.

Dim rand = New Random()

For counter = 0 to Cards.Length - 1

  Dim n = rand.Next(counter + 1)

  Dim temp = Cards(counter)
  Cards(counter) = Cards(n)
  Cards(n) = temp