Reputation: 2224
I'm wondering how to create a multidimensional array that can hold both Integers and Strings.
I'm creating an array to hold playing cards:
deck(0, 0) = 2
deck(0, 1) = Hearts
I'd also like to shuffle the array. What's the best way to do this?
Upvotes: 2
Views: 6510
Reputation: 6948
Extending the idea of using a class, a class including an array of cards with a new constructor and a shuffle method will tidy things up:
Public Class Card
Public Property Value As Integer = 0
Public Property Suit As Suits
Enum Suits
Hearts = 1
Clubs = 2
Spades = 3
Diamonds = 4
End Enum
Public Overrides Function ToString() As String
Return Value.ToString + "of" + Suit.ToString
End Function
End Class
Public Class Deck
Public Shared Cards(51) As Card
Shared Sub New()
For I = 1 To 4
Dim CurrentSuit = CType([Enum].ToObject(GetType(Card.Suits), I), Card.Suits)
For J = 1 To 13
Cards((((I - 1) * 13) + J) - 1) = New Card With {.Value = J, .Suit = CurrentSuit}
Next
Next
End Sub
Public Sub Shuffle()
Dim rnd As New Random(Now.Millisecond)
For i = 0 To 51
Dim tempindex = rnd.Next(0, 52)
Dim tempcard = Cards(tempindex)
Cards(tempindex) = Cards(i)
Cards(i) = tempcard
Next
End Sub
End Class
Dim CurrentDeck As New Deck()
will initialize the deck will all the cards in order. Calling the Shuffle
method will shuffle the cards ready for dealing(CurrentDeck.Shuffle
).
Upvotes: 1
Reputation: 700612
You shouldn't use multidimensional arrays like that, for several reasons:
If you want to mix data types, the array type would be object, and you need to cast every value when you use them.
The relation between the values that belong together is just in the code that you write, so you have no help from the compiler to keep you from mixing values from different items.
The properties for an item is just identified by a number, it would be better to give it a name.
Create a custom class for the items:
Public Class Card
Public Property Value As Integer
Public Property Suit As String
End Class
Dim deck As New List(Of Card)
Or use one that exist:
Dim deck As New List(Of Tuple(Of Integer, String))
The Tuple
class is easy to use as it already exists, however the names of the properties (Item1
and Item2
) isn't very descriptive.
Upvotes: 2