2
\$\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\$
0

1 Answer 1

5
\$\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\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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