384.shuffle-an-array.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. //package main
  2. //import (
  3. // "fmt"
  4. // "math/rand"
  5. //)
  6. type Solution struct {
  7. arr []int
  8. sol []int
  9. }
  10. func Constructor(nums []int) Solution {
  11. solution := Solution{arr: nums}
  12. solution.sol = make([]int, len(nums))
  13. copy(solution.sol, nums)
  14. return solution
  15. }
  16. /** Resets the array to its original configuration and return it. */
  17. func (this *Solution) Reset() []int {
  18. copy(this.sol, this.arr)
  19. return this.arr
  20. }
  21. /** Returns a random shuffling of the array. */
  22. func (this *Solution) Shuffle() []int {
  23. n := len(this.arr)
  24. for i := 0; i < n; i++ {
  25. j := i + rand.Intn(n-i)
  26. this.sol[i], this.sol[j] = this.sol[j], this.sol[i]
  27. }
  28. return this.sol
  29. }
  30. //type tuple3 struct {
  31. // _1 int
  32. // _2 int
  33. // _3 int
  34. //}
  35. //func main() {
  36. // sol := Constructor([]int{1, 2, 3})
  37. // m := make(map[tuple3]int)
  38. // for i := 0; i < 10000; i++ {
  39. // arr := sol.Shuffle()
  40. // m[tuple3{arr[0], arr[1], arr[2]}]++
  41. // }
  42. // fmt.Println(m)
  43. //}
  44. /**
  45. * Your Solution object will be instantiated and called as such:
  46. * obj := Constructor(nums);
  47. * param_1 := obj.Reset();
  48. * param_2 := obj.Shuffle();
  49. */