Refactor Strip (already).

Stripping cards from the Hand will also be useful, so I pulled the logic of Strip out into arrayutil (more efficiently, too) and rewrote deck.Strip to use it.
This commit is contained in:
Kistaro Windrider 2023-04-01 19:40:28 -07:00
parent 222d4375ee
commit 75de281cee
Signed by: kistaro
SSH Key Fingerprint: SHA256:TBE2ynfmJqsAf0CP6gsflA0q5X5wD5fVKWPsZ7eVUg8
2 changed files with 22 additions and 18 deletions

View File

@ -275,22 +275,7 @@ func (d *Deck[C]) ShuffleBottom(frac float64) error {
// shouldRemove is provided with each card in the deck and its index.
// It returns how many cards were stripped from the deck.
func (d *Deck[C]) Strip(shouldRemove func(idx int, c Card[C]) bool) int {
stripped := 0
startStripRange := -1
for i := 0; i < len(d.cards); i++ {
if shouldRemove(i, d.cards[i]) {
stripped++
if startStripRange < 0 {
startStripRange = i
}
} else if startStripRange >= 0 {
d.cards = DeleteNFrom(d.cards, startStripRange, i-startStripRange)
i = startStripRange
startStripRange = -1
}
}
if startStripRange >= 0 {
d.cards = d.cards[:startStripRange]
}
return stripped
origLen := d.Len()
d.cards = Strip(d.cards, shouldRemove)
return origLen - d.Len()
}

View File

@ -126,3 +126,22 @@ func ShufflePart[T any](slice []T, r *rand.Rand, loc, n int) {
}
ShuffleAll(slice[loc:loc+n], r)
}
// Strip iterates T, removing any element for which removeWhen returns true
// (when provided the index of the element and the element itself as arguments).
// It returns the stripped slice.
func Strip[T any](slice []T, removeWhen func(idx int, t T) bool) []T {
if len(slice) == 0 {
return nil
}
to := 0
for from, e := range slice {
if !removeWhen(from, e) {
if to != from {
slice[to] = slice[from]
}
to++
}
}
return slice[:to]
}