1

I am trying to simulate a multiple deck drawing using an array. After the first card is dealt, how can I remove this random number ("p1") from the deck array, so I can have an array with 51 elements without the first one to be selected?

That`s how I am doing it so far

Dim deck(1 To 52) As Variant
Dim p1 As Integer


For i = 1 To 52

    deck(i) = i

Next

p1 = Int((UBound(deck) * Rnd) + 1)
  • Possible duplicate of [Remove the first element of a VBA array](https://stackoverflow.com/questions/34231734/remove-the-first-element-of-a-vba-array) – 41686d6564 stands w. Palestine Oct 21 '19 at 00:24
  • 1
    My VBA is really rusty, but I think when you create your deck as a `Collection` instead of an array, you will have easier control over your deck. A collection allows for simple adding and removeing of elements. – Rno Oct 21 '19 at 00:42
  • 1
    Welcome to SO! When you place a question try to add a minimum content: input sample, expected output sample, what did you try, research and where are you stacked. Your question is clear, but what did you try? How are you trying to remove one element? – David García Bodego Oct 21 '19 at 03:32

2 Answers2

1

I could solve it with the code below but I am still wondering if there is an easier way

Sub preflop()

Dim deck() As Integer
Dim p1 As Integer


For i = 1 To 52
    ReDim Preserve deck(1 To i) As Integer
    deck(i) = i
Next

p1 = Int((UBound(deck) * Rnd) + 1)

For i = LBound(deck) To UBound(deck)
    If deck(i) = p1 Then
        For j = i To UBound(deck) - 1
            deck(j) = deck(j + 1)
        Next
    End If
Next

ReDim Preserve deck(1 To UBound(deck) - 1) As Integer


End Sub
  • You can look in either a VBA collection or .NET arraylist. You can delete items per index number from these class objects. – JvdV Oct 21 '19 at 04:39
1

As per my comment, here an example on how you can utilize an ArrayList for this purpose:

Sub preflop()

Dim arr As Object: Set arr = CreateObject("System.Collections.ArrayList")
Dim item As Variant, ResultArr As Variant
Dim i As Long, p1 As Long

With arr

    'Load all variables
    For i = 1 To 52
        .Add i
    Next i

    'Get random number
    p1 = ((.Count - 1) - 1) * Rnd

    'Remove the random card from the deck
    .Remove (p1)

    'To use an array in further code somewhere
    ResultArr = .Toarray

End With

End Sub

AFAIK the use of ArrayList over the more native Collection will open ways to use methods like Toarray to export the arrayList to an array without an expensive Redim loop.

If you don't need to end up with an array you might as well use the Collection approach.

JvdV
  • 70,606
  • 8
  • 39
  • 70