Friday, November 29, 2013

VBA Simulation of Shuffling and Distributing a Deck of Cards

Here's a simple VBA program that simulates shuffling and distributing a standard deck of 52 cards to 4 players. The program outputs the results in cells A1 through D13 of the current Excel spreadsheet, with the 4 rows corresponding to the 4 players' cards.
Sub ShuffleCards()
'This program simulates shuffling of a standard deck of 52 cards to 4 players
'Results are outputted in 4 columns in cells A1:D13

'H: heart, S: spades, D: diamod, C: club
'2 thru 10, J for jack, Q for queen, K for king, A for ace
'2H would be 2 of hearts, KD would be king of diamonds, etc.

'Creating
suits = Array("H", "S", "D", "C")
num = Array("2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A")

Dim cards(0 To 51) As String
For i = 0 To 3
For j = 0 To 12
cards(13 * i + j) = num(j) & suits(i)
Next j
Next i

'Shuffling
For i = 1 To 1000
c1 = Int(52 * Rnd)
c2 = Int(52 * Rnd)
temp = cards(c1)
cards(c1) = cards(c2)
cards(c2) = temp
Next i
'Distributing
For k = 0 To 51
Cells(k Mod 13 + 1, Int(k / 13) + 1) = cards(k)
Next k
End Sub

The shuffling algorithm is to run through 1000 iterations of swapping two randomly chosen cards.