analytics.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package main
  2. import "sort"
  3. type analytic struct {
  4. Key string
  5. Count int
  6. Percentage float64
  7. }
  8. type analyticList []analytic
  9. func (l analyticList) Less(a, b int) bool {
  10. return l[b].Count < l[a].Count // inverse
  11. }
  12. func (l analyticList) Swap(a, b int) {
  13. l[a], l[b] = l[b], l[a]
  14. }
  15. func (l analyticList) Len() int {
  16. return len(l)
  17. }
  18. // Returns a list of frequency analytics for a given list of strings.
  19. func analyticsFor(ss []string, cutoff int) []analytic {
  20. m := make(map[string]int)
  21. t := 0
  22. for _, s := range ss {
  23. m[s]++
  24. t++
  25. }
  26. l := make([]analytic, 0, len(m))
  27. for k, c := range m {
  28. l = append(l, analytic{k, c, 100 * float64(c) / float64(t)})
  29. }
  30. sort.Sort(analyticList(l))
  31. if cutoff > 0 && len(l) > cutoff {
  32. c := 0
  33. for _, i := range l[cutoff:] {
  34. c += i.Count
  35. }
  36. l = append(l[:cutoff], analytic{"Others", c, 100 * float64(c) / float64(t)})
  37. }
  38. return l
  39. }
  40. func statsForInts(data []int) [4]float64 {
  41. var res [4]float64
  42. if len(data) == 0 {
  43. return res
  44. }
  45. sort.Ints(data)
  46. res[0] = float64(data[int(float64(len(data))*0.05)])
  47. res[1] = float64(data[len(data)/2])
  48. res[2] = float64(data[int(float64(len(data))*0.95)])
  49. res[3] = float64(data[len(data)-1])
  50. return res
  51. }
  52. func statsForFloats(data []float64) [4]float64 {
  53. var res [4]float64
  54. if len(data) == 0 {
  55. return res
  56. }
  57. sort.Float64s(data)
  58. res[0] = data[int(float64(len(data))*0.05)]
  59. res[1] = data[len(data)/2]
  60. res[2] = data[int(float64(len(data))*0.95)]
  61. res[3] = data[len(data)-1]
  62. return res
  63. }