Advertisement
Guest User

Untitled

a guest
Jul 25th, 2016
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.87 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "math/rand"
  6. "time"
  7. )
  8.  
  9. func main() {
  10. // shuffle local
  11. hosts := []string{"a", "b", "c", "d", "e", "f"}
  12. shuffle(len(hosts), func(i, j int) {
  13. hosts[i], hosts[j] = hosts[j], hosts[i]
  14. })
  15.  
  16. fmt.Println("shuffle string: ", hosts)
  17.  
  18. ints := []int{1, 2, 3, 4, 5, 6}
  19. shuffle(len(ints), func(i, j int) {
  20. ints[i], ints[j] = ints[j], ints[i]
  21. })
  22. fmt.Println("shuffle int: ", ints)
  23.  
  24. // shuffle new
  25. nhosts := []string{"a", "b", "c", "d", "e", "f"}
  26. new_nhosts := make([]string, len(nhosts))
  27. copy(new_nhosts, nhosts)
  28. shuffle(len(hosts), func(i, j int) {
  29. new_nhosts[i], new_nhosts[j] = new_nhosts[j], new_nhosts[i]
  30. })
  31.  
  32. fmt.Println("origin : ", nhosts)
  33. fmt.Println("new : ", new_nhosts)
  34. }
  35.  
  36. func shuffle(length int, exchange func(int, int)) {
  37. rand.Seed(int64(time.Now().Nanosecond()))
  38. for i := length - 1; i > 0; i-- {
  39. j := rand.Intn(i)
  40. exchange(i, j)
  41. }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement