Created
June 7, 2013 21:09
-
-
Save marcelom/5732441 to your computer and use it in GitHub Desktop.
Go Slice Shuffle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"math/rand" | |
"time" | |
) | |
func Shuffle(a []int) { | |
for i := range a { | |
j := rand.Intn(i + 1) | |
a[i], a[j] = a[j], a[i] | |
} | |
} | |
func main() { | |
a := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} | |
rand.Seed(time.Now().UnixNano()) | |
Shuffle(a) | |
fmt.Println(a) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Take a look at rand.Perm -- might save the need to call rand.Int inside the loop.