util.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. package gago
  2. import (
  3. "math"
  4. )
  5. func newInts(n int) []int {
  6. var ints = make([]int, n)
  7. for i := range ints {
  8. ints[i] = i
  9. }
  10. return ints
  11. }
  12. // Divide each element in a float64 slice by a given value.
  13. func divide(floats []float64, value float64) []float64 {
  14. var divided = make([]float64, len(floats))
  15. for i, v := range floats {
  16. divided[i] = v / value
  17. }
  18. return divided
  19. }
  20. // Compute the cumulative sum of a float64 slice.
  21. func cumsum(floats []float64) []float64 {
  22. var summed = make([]float64, len(floats))
  23. copy(summed, floats)
  24. for i := 1; i < len(summed); i++ {
  25. summed[i] += summed[i-1]
  26. }
  27. return summed
  28. }
  29. // Find the minimum between two ints.
  30. func min(a, b int) int {
  31. if a <= b {
  32. return a
  33. }
  34. return b
  35. }
  36. // Compute the sum of an int slice.
  37. func sumInts(ints []int) (sum int) {
  38. for _, v := range ints {
  39. sum += v
  40. }
  41. return
  42. }
  43. // Compute the sum of a float64 slice.
  44. func sumFloat64s(floats []float64) (sum float64) {
  45. for _, v := range floats {
  46. sum += v
  47. }
  48. return
  49. }
  50. // Compute the minimum value of a float64 slice.
  51. func minFloat64s(floats []float64) (min float64) {
  52. min = math.Inf(1)
  53. for _, f := range floats {
  54. if f < min {
  55. min = f
  56. }
  57. }
  58. return
  59. }
  60. // Compute the maximum value of a float64 slice.
  61. func maxFloat64s(floats []float64) (max float64) {
  62. max = math.Inf(-1)
  63. for _, f := range floats {
  64. if f > max {
  65. max = f
  66. }
  67. }
  68. return
  69. }
  70. // Compute the mean of a float64 slice.
  71. func meanFloat64s(floats []float64) float64 {
  72. return sumFloat64s(floats) / float64(len(floats))
  73. }
  74. // Compute the variance of a float64 slice.
  75. func varianceFloat64s(floats []float64) float64 {
  76. var (
  77. m = meanFloat64s(floats)
  78. ss float64
  79. )
  80. for _, x := range floats {
  81. ss += math.Pow(x-m, 2)
  82. }
  83. return ss / float64(len(floats))
  84. }
  85. type set map[interface{}]bool
  86. // union merges two slices and ignores duplicates.
  87. func union(x, y set) set {
  88. var (
  89. u = make(set)
  90. blackList = make(map[interface{}]bool)
  91. )
  92. for i := range x {
  93. u[i] = true
  94. blackList[i] = true
  95. }
  96. for i := range y {
  97. if !blackList[i] {
  98. u[i] = true
  99. blackList[i] = true
  100. }
  101. }
  102. return u
  103. }