Browse Source

Use Fisher-Yates shuffle algorithm

master v0.1.4
Trevor Slocum 2 years ago
parent
commit
94970324dc
  1. 3
      CHANGELOG
  2. 11
      deck.go

3
CHANGELOG

@ -1,3 +1,6 @@ @@ -1,3 +1,6 @@
0.1.4:
- Use Fisher-Yates shuffle algorithm
0.1.3:
- Add Cards.Remove

11
deck.go

@ -9,7 +9,7 @@ import ( @@ -9,7 +9,7 @@ import (
type Deck struct {
Cards Cards
r *rand.Rand
rand *rand.Rand
}
// NewDeck initializes a deck of cards. A seed value of 0 is replaced with the
@ -19,13 +19,14 @@ func NewDeck(c Cards, seed int64) *Deck { @@ -19,13 +19,14 @@ func NewDeck(c Cards, seed int64) *Deck {
seed = time.Now().UnixNano()
}
return &Deck{Cards: c.Copy(), r: rand.New(rand.NewSource(seed))}
return &Deck{Cards: c.Copy(), rand: rand.New(rand.NewSource(seed))}
}
// Shuffle randomizes the deck.
// Shuffle randomizes the order of the deck using the Fisher-Yates shuffle
// algorithm.
func (d *Deck) Shuffle() {
for i := range d.Cards {
j := d.r.Intn(i + 1)
for i := len(d.Cards) - 1; i > 0; i-- {
j := d.rand.Intn(i + 1)
d.Cards[i], d.Cards[j] = d.Cards[j], d.Cards[i]
}
}

Loading…
Cancel
Save