From 75de281ceeb73e0cfa23109be6bd1ceb1d128b10 Mon Sep 17 00:00:00 2001 From: Kistaro Windrider Date: Sat, 1 Apr 2023 19:40:28 -0700 Subject: [PATCH] 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. --- cardsim/deck.go | 21 +++------------------ cardsim/sliceutil.go | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+), 18 deletions(-) diff --git a/cardsim/deck.go b/cardsim/deck.go index b888150..627ea70 100644 --- a/cardsim/deck.go +++ b/cardsim/deck.go @@ -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() } diff --git a/cardsim/sliceutil.go b/cardsim/sliceutil.go index e64207e..704731b 100644 --- a/cardsim/sliceutil.go +++ b/cardsim/sliceutil.go @@ -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] +}