Skip to content

Instantly share code, notes, and snippets.

@reedobrien
Created September 9, 2015 17:38
Show Gist options
  • Save reedobrien/5c2938e500c1b9eb7a87 to your computer and use it in GitHub Desktop.
Save reedobrien/5c2938e500c1b9eb7a87 to your computer and use it in GitHub Desktop.
given a slice of 52 slots shuffle so that the result has a uniform distribution probability
package main
import (
"fmt"
"math/rand"
"time"
)
// given array of 52 slots shuffle so that the result has a uniform distribution probability
var (
deck []int
shuffled []int
)
func Shuffle(deck []int) []int {
rand.Seed(time.Now().UnixNano())
for i := len(deck); i > 0; i-- {
// pick an index
index := rand.Intn(len(deck))
// get the value
newcard := deck[index]
// Put it in the new deck
shuffled = append(shuffled, newcard)
// Remove from the original
deck = append(deck[:index], deck[index+1:]...)
}
return shuffled
}
func main() {
// Build a deck
for i := 0; i < 52; i++ {
deck = append(deck, i)
}
fmt.Printf("Unshuffled deck: %v\n", deck)
shuffled = Shuffle(deck)
fmt.Printf("%d slots shuffled: %v\n", len(shuffled), shuffled)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment