Home » excel » excel – Removing an element from an integer array

# excel – Removing an element from an integer array

Questions:

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)
``````

## 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
``````

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

For i = 1 To 52
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.