Shuffling an array of cards

I have a deck of flashcards that I want to shuffle. Here's the method I'm using to shuffle them:

func (deck *Deck) Shuffle() {
rand.Seed(time.Now().UnixNano())
randomIndexes := rand.Perm(len(deck.Cards))

shuffledCards := make([]Card, len(deck.Cards))
for i := 0; i < len(deck.Cards); i++ {
shuffledCards[i] = deck.Cards[randomIndexes[i]]
}

deck.Cards = shuffledCards
}


Is this an efficient way of doing it, or is there a better way?

I would recommend something closer to a Knuth shuffle, where you swap items in place in the array, rather then allocating a new one.

This is untested and is based on the Fisher-Yates shuffle:

func (deck *Deck) Shuffle() {
rand.Seed(time.Now().UnixNano())

for i := len(deck.Cards)-1; i > 0; i-- {
j := rand.Intn(i+1) // i+1 rather than i; the upper bound is not inclusive
deck.Cards[i], deck.Cards[j] = deck.Cards[j], deck.Cards[i]
}
}


Unrelated to shuffling, you should also check out bucketed flashcards. Consider the Leitner system.

• Simple and Efficient. Thanks for the link :) – W.K.S Jan 1 '14 at 12:42