github.com/coyove/common@v0.0.0-20240403014525-f70e643f9de8/goal/main_test.go (about) 1 package goal 2 3 import ( 4 "math/rand" 5 "testing" 6 "time" 7 ) 8 9 func TestGoal(t *testing.T) { 10 g := New() 11 g.Meet(0) 12 g.Meet(0) 13 g.Meet(1) 14 g.Meet(2) 15 g.Meet(4) 16 g.Meet(3) 17 for i := 5; i < 10; i++ { 18 g.Meet(uint64(i)) 19 } 20 21 if g.Goal() != 10 || g.Overflow() != 0 { 22 t.FailNow() 23 } 24 25 g.Meet(11) 26 if g.Goal() != 10 || g.Overflow() != 1 { 27 t.FailNow() 28 } 29 30 g.Meet(10) 31 // we don't check 11 now, if we add 12 (or onward), we will then cehck 11 32 if g.Goal() != 11 || g.Overflow() != 1 { 33 t.FailNow() 34 } 35 36 g.Meet(12) 37 if g.Goal() != 13 || g.Overflow() != 0 { 38 t.FailNow() 39 } 40 41 // 12 has been met, meeting it again will return false 42 if g.Meet(12) != false { 43 t.FailNow() 44 } 45 } 46 47 func TestGoalRandom(t *testing.T) { 48 r := rand.New(rand.NewSource(time.Now().UnixNano())) 49 x := r.Perm(65536) 50 g := New() 51 for _, num := range x { 52 g.Meet(uint64(num)) 53 } 54 55 g.Meet(65536) 56 if g.Goal() != 65537 || g.Overflow() != 0 { 57 t.FailNow() 58 } 59 60 for i := 0; i < 65537; i++ { 61 if g.Meet(uint64(i)) != false { 62 t.FailNow() 63 } 64 } 65 } 66 67 func BenchmarkGoalRandom(b *testing.B) { 68 r := rand.New(rand.NewSource(time.Now().UnixNano())) 69 x := r.Perm(65536) 70 for i := 0; i < b.N; i++ { 71 g := New() 72 for _, num := range x { 73 g.Meet(uint64(num)) 74 } 75 g.Meet(65536) 76 if g.Goal() != 65537 || g.Overflow() != 0 { 77 b.FailNow() 78 } 79 } 80 } 81 82 func BenchmarkGoalLessRandom(b *testing.B) { 83 r := rand.New(rand.NewSource(time.Now().UnixNano())) 84 x := make([]uint64, 65536) 85 for i := 0; i < len(x); i++ { 86 x[i] = uint64(i) 87 } 88 89 for i := 0; i < len(x); i++ { 90 if r.Intn(100) != 0 { 91 continue 92 } 93 94 j := r.Intn(10) + i - 20 95 96 if j >= 0 && i < len(x) { 97 x[i], x[j] = x[j], x[i] 98 } 99 } 100 101 for i := 0; i < b.N; i++ { 102 g := New() 103 for _, num := range x { 104 g.Meet(uint64(num)) 105 } 106 g.Meet(65536) 107 if g.Goal() != 65537 || g.Overflow() != 0 { 108 b.FailNow() 109 } 110 } 111 }