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?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Dec 28, 2013 at 20:29
\$\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.

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
answered Dec 28, 2013 at 22:26
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.