Skip to content

Instantly share code, notes, and snippets.

@mapix
Created July 25, 2016 06:09
Show Gist options
  • Save mapix/c86e0489861d5f51f93b94d2031ec1c5 to your computer and use it in GitHub Desktop.
Save mapix/c86e0489861d5f51f93b94d2031ec1c5 to your computer and use it in GitHub Desktop.
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)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment