You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

51 lines
1.3 KiB

  1. package rand
  2. import (
  3. "math/rand"
  4. "sync"
  5. )
  6. // Int returns a non-negative pseudo-random int.
  7. func Int() int { return pseudo.Int() }
  8. // Intn returns, as an int, a non-negative pseudo-random number in [0,n).
  9. // It panics if n <= 0.
  10. func Intn(n int) int { return pseudo.Intn(n) }
  11. // Int63n returns, as an int64, a non-negative pseudo-random number in [0,n).
  12. // It panics if n <= 0.
  13. func Int63n(n int64) int64 { return pseudo.Int63n(n) }
  14. // Perm returns, as a slice of n ints, a pseudo-random permutation of the integers [0,n).
  15. func Perm(n int) []int { return pseudo.Perm(n) }
  16. // Seed uses the provided seed value to initialize the default Source to a
  17. // deterministic state. If Seed is not called, the generator behaves as if
  18. // seeded by Seed(1).
  19. func Seed(n int64) { pseudo.Seed(n) }
  20. var pseudo = rand.New(&source{src: rand.NewSource(1)})
  21. type source struct {
  22. src rand.Source
  23. mu sync.Mutex
  24. }
  25. func (s *source) Int63() int64 {
  26. s.mu.Lock()
  27. n := s.src.Int63()
  28. s.mu.Unlock()
  29. return n
  30. }
  31. func (s *source) Seed(seed int64) {
  32. s.mu.Lock()
  33. s.src.Seed(seed)
  34. s.mu.Unlock()
  35. }
  36. // Shuffle pseudo-randomizes the order of elements.
  37. // n is the number of elements.
  38. // swap swaps the elements with indexes i and j.
  39. func Shuffle(n int, swap func(i, j int)) { pseudo.Shuffle(n, swap) }