Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- "math/rand"
- "time"
- )
- func main() {
- // shuffle local
- hosts := []string{"a", "b", "c", "d", "e", "f"}
- shuffle(len(hosts), func(i, j int) {
- hosts[i], hosts[j] = hosts[j], hosts[i]
- })
- fmt.Println("shuffle string: ", hosts)
- ints := []int{1, 2, 3, 4, 5, 6}
- shuffle(len(ints), func(i, j int) {
- ints[i], ints[j] = ints[j], ints[i]
- })
- fmt.Println("shuffle int: ", ints)
- // shuffle new
- nhosts := []string{"a", "b", "c", "d", "e", "f"}
- new_nhosts := make([]string, len(nhosts))
- copy(new_nhosts, nhosts)
- shuffle(len(hosts), func(i, j int) {
- new_nhosts[i], new_nhosts[j] = new_nhosts[j], new_nhosts[i]
- })
- fmt.Println("origin : ", nhosts)
- fmt.Println("new : ", new_nhosts)
- }
- func shuffle(length int, exchange func(int, int)) {
- rand.Seed(int64(time.Now().Nanosecond()))
- for i := length - 1; i > 0; i-- {
- j := rand.Intn(i)
- exchange(i, j)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement