util_random_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. package gago
  2. import (
  3. "errors"
  4. "math"
  5. "math/rand"
  6. "testing"
  7. "time"
  8. )
  9. func TestRandomInts(t *testing.T) {
  10. var (
  11. src = rand.NewSource(time.Now().UnixNano())
  12. rng = rand.New(src)
  13. testCases = []struct {
  14. k, min, max int
  15. }{
  16. {1, 0, 1},
  17. {1, 0, 2},
  18. {2, 0, 2},
  19. }
  20. )
  21. for _, test := range testCases {
  22. var ints = randomInts(test.k, test.min, test.max, rng)
  23. // Check the number of generated integers
  24. if len(ints) != test.k {
  25. t.Error("randomInts didn't generate the right number of integers")
  26. }
  27. // Check the bounds of each generated integer
  28. for _, integer := range ints {
  29. if integer < test.min || integer >= test.max {
  30. t.Error("randomInts didn't generate integers in the desired range")
  31. }
  32. }
  33. // Check the generated integers are unique
  34. for i, a := range ints {
  35. for j, b := range ints {
  36. if i != j && a == b {
  37. t.Error("randomInts didn't generate unique integers")
  38. }
  39. }
  40. }
  41. }
  42. }
  43. func TestSampleInts(t *testing.T) {
  44. var testCases = []struct {
  45. ints []int
  46. k int
  47. err error
  48. }{
  49. {
  50. ints: []int{1, 2, 3},
  51. k: 0,
  52. err: nil,
  53. },
  54. {
  55. ints: []int{1, 2, 3},
  56. k: 1,
  57. err: nil,
  58. },
  59. {
  60. ints: []int{1, 2, 3},
  61. k: 2,
  62. err: nil,
  63. },
  64. {
  65. ints: []int{1, 2, 3},
  66. k: 3,
  67. err: nil,
  68. },
  69. {
  70. ints: []int{1, 2, 3},
  71. k: 4,
  72. err: errors.New("k > len(ints)"),
  73. },
  74. }
  75. var rng = newRandomNumberGenerator()
  76. for i, tc := range testCases {
  77. var ints, idxs, err = sampleInts(tc.ints, tc.k, rng)
  78. if (err == nil) != (tc.err == nil) {
  79. t.Errorf("Error in test case number %d", i)
  80. } else {
  81. if err == nil && (len(ints) != tc.k || len(idxs) != tc.k) {
  82. t.Errorf("Error in test case number %d", i)
  83. }
  84. }
  85. }
  86. }
  87. func TestRandomWeights(t *testing.T) {
  88. var (
  89. sizes = []int{1, 30, 500}
  90. limit = math.Pow(1, -10)
  91. )
  92. for _, size := range sizes {
  93. var weights = randomWeights(size)
  94. // Test the length of the resulting slice
  95. if len(weights) != size {
  96. t.Error("Size problem with randomWeights")
  97. }
  98. // Test the elements in the slice sum up to 1
  99. var sum float64
  100. for _, weight := range weights {
  101. sum += weight
  102. }
  103. if math.Abs(sum-1.0) > limit {
  104. t.Error("Sum problem with randomWeights")
  105. }
  106. }
  107. }