From b806264154aa8ebdb06c4051df65a19cdbb09ee4 Mon Sep 17 00:00:00 2001 From: Kistaro Windrider Date: Sat, 1 Apr 2023 19:23:14 -0700 Subject: [PATCH] Fraction-specified shufflers. Convenience methods for "shuffle the bottom third of the deck" and stuff like that. --- cardsim/deck.go | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/cardsim/deck.go b/cardsim/deck.go index cca7381..28214a6 100644 --- a/cardsim/deck.go +++ b/cardsim/deck.go @@ -238,3 +238,35 @@ func (d *Deck[C]) ShufflePart(loc, n int) error { ShufflePart(d.cards, d.rand, loc, n) return nil } + +// ShuffleRange shuffles the cards between the specified fractions of +// the deck; the top of the deck is 0.0 and the bottom of the deck is +// 1.0. This rounds "outward" -- "partial" cards at each end are counted. +// This can return the same warnings ShufflePart can in the same circumstances +// and may also complain about a backwards range. +func (d *Deck[C]) ShuffleRange(loFrac, hiFrac float64) error { + var errs ErrorCollector + if loFrac > hiFrac { + errs.Add(Warningf("%w: %f > %f", WarningBackwardsRange, loFrac, hiFrac)) + loFrac, hiFrac = hiFrac, loFrac + } + low := int(math.Floor(loFrac * float64(d.Len()))) + high := int(math.Ceil(hiFrac * float64(d.Len()))) + n := 1 + high - low + errs.Add(d.ShufflePart(low, n)) + return errs.Emit() +} + +// ShuffleTop uses ShuffleRange to shuffle the top frac (between 0.0 and 1.0) +// of the deck. See ShuffleRange and ShufflePart for information on +// rounding and warnings. +func (d *Deck[C]) ShuffleTop(frac float64) error { + return d.ShuffleRange(0.0, frac) +} + +// Shufflebottom uses ShuffleRange to shuffle the bottom frac (between 0.0 and +// 1.0) of the deck. See ShuffleRange and ShufflePart for information on +// rounding and warnings. +func (d *Deck[C]) ShuffleBottom(frac float64) error { + return d.ShuffleRange(frac, 1.0) +}