weighter_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. package weightrand
  2. import (
  3. "fmt"
  4. "math/rand"
  5. "testing"
  6. "time"
  7. )
  8. func TestWeightRand(t *testing.T) {
  9. rand.Seed(time.Now().Unix())
  10. wr := NewRandTable[string]()
  11. wr.AddItem("C", 1)
  12. wr.AddItem("A", 10)
  13. wr.AddItem("B", 30)
  14. wr.AddItem("D", 59)
  15. wr.AddItem("E", 0)
  16. results := map[string]int{
  17. "A": 0,
  18. "B": 0,
  19. "C": 0,
  20. "D": 0,
  21. "E": 0,
  22. }
  23. iterations := 10000
  24. for i := 0; i < iterations; i++ {
  25. id, ok := wr.GetRandomItem()
  26. if !ok {
  27. break
  28. }
  29. results[id]++
  30. }
  31. // Print the results
  32. fmt.Printf("Results after %d iterations:\n", iterations)
  33. for item, count := range results {
  34. fmt.Printf("%s: %f%%\n", item, float64(count)/float64(iterations)*100)
  35. }
  36. }
  37. func TestWeightRand2(t *testing.T) {
  38. rand.Seed(time.Now().Unix())
  39. wr := NewRandTable[string]()
  40. wr.AddItem("C", 1)
  41. wr.AddItem("A", 10)
  42. wr.AddItem("B", 30)
  43. wr.AddItem("D", 59)
  44. wr.AddItem("E", 0)
  45. results := map[string]int{
  46. "A": 0,
  47. "B": 0,
  48. "C": 0,
  49. "D": 0,
  50. "E": 0,
  51. }
  52. iterations := 10
  53. count := 0
  54. for i := 0; i < iterations; i++ {
  55. id, ok := wr.RandomRemoveItem()
  56. if !ok {
  57. break
  58. }
  59. results[id]++
  60. count++
  61. }
  62. fmt.Printf("Rand count %d \n", count)
  63. // Print the results
  64. fmt.Printf("Results after %d iterations:\n", iterations)
  65. for item, count := range results {
  66. fmt.Printf("%s: %f%%\n", item, float64(count)/float64(iterations)*100)
  67. }
  68. }
  69. //
  70. //func TestSimpleWeightRand(t *testing.T) {
  71. // rand.Seed(time.Now().Unix())
  72. // wr := NewSimpleRandTable(4)
  73. //
  74. // wr.AddItem(0)
  75. // wr.AddItem(10)
  76. // wr.AddItem(30)
  77. // wr.AddItem(60)
  78. //
  79. // results := map[int]int{
  80. // 0: 0,
  81. // 1: 0,
  82. // 2: 0,
  83. // 3: 0,
  84. // }
  85. //
  86. // iterations := 10000
  87. //
  88. // for i := 0; i < iterations; i++ {
  89. // item := wr.GetRandomItem()
  90. // results[item]++
  91. // }
  92. //
  93. // // Print the results
  94. // fmt.Printf("Results after %d iterations:\n", iterations)
  95. // for item, count := range results {
  96. // fmt.Printf("%d: %f%%\n", item, float64(count)/float64(iterations)*100)
  97. // }
  98. //}