rsprodftw1 rsprodftw1 - 1 year ago 88 Question

BlackJack deck, shuffling the cards

For some reason in this code, my s.Remove() isn't working. Can anybody tell me why and help me come up with a solution??

Private Sub ShuffleDeck()
Dim sb As New System.Text.StringBuilder
Dim s As String = "23456789bJQKA23456789bJQKA23456789bJQKA23456789bJQKA23456789bJQKA23456789bJQKA23456789bJQKA23456789bJQKA23456789bJQKA23456789bJQKA23456789bJQKA23456789bJQKA23456789bJQKA23456789bJQKA23456789bJQKA23456789bJQKA"
For i As Integer = 1 To prng.Next(208, 208)
Dim rndCard As String = prng.Next(0, s.Length)
sb.Append(s.Substring(rndCard), 1)
s.Remove(rndCard, 1)
deck = sb.ToString()
End Sub

I have it there so my deck doesn't have 20 2s and 15 3s and so on... There's supposed to be 16 of each number and face card since this is a game with 4 decks.

Answer Source

Iterating from 1 To prng.Next(208, 208) does not make any sense. The latter will always return 208, so no need to put a Random there.

As to why it's not working: s.Remove(rndCard, 1) returns a new String instance from which the chosen character has been removed. You need to reassign that new String to your s.

But as you can guess, this is not optimal in terms of performance because you are creating new String objects during each iteration. A better way might be to make your s into a StringBuilder as well, so you can remove things in place without creating new instances.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download