1
\$\begingroup\$

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?

\$\endgroup\$
4
\$\begingroup\$

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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.