本文整理汇总了Golang中math/rand.Int31n函数的典型用法代码示例。如果您正苦于以下问题:Golang Int31n函数的具体用法?Golang Int31n怎么用?Golang Int31n使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Int31n函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: MakeTestTasksN
func MakeTestTasksN(height, width, connectivity int) graph.Tasks {
t := make(graph.Tasks)
levels := make([][]*graph.Task, height)
for i := range levels {
levels[i] = make([]*graph.Task, width)
for j := range levels[i] {
task := &graph.Task{
Id: graph.TaskID(strconv.FormatInt(rand.Int63(), 10)),
Start: rand.Int63(),
End: rand.Int63(),
Completed: rand.Int()%2 == 0,
Dependencies: graph.MakeTaskIDSet(),
}
t[task.Id] = task
levels[i][j] = task
}
}
for depth, level := range levels[:height-1] {
for _, task := range level {
connections := rand.Int31n(int32(connectivity))
for i := 0; i < int(connections); i++ {
row, col := rand.Int31n(int32(height-depth-1)), rand.Int31n(int32(width))
task.Dependencies.Add(levels[depth+int(row)+1][col].Id)
}
}
}
return t
}
示例2: send
func send() {
channelGoCount <- 1
// fmt.Println("tick")
conn, err := net.DialTimeout("tcp", fmt.Sprintf("%v:%v", S.ServerAddr, S.Port_to_listen), time.Duration(10+rand.Int31n(delay))*time.Millisecond)
if err == nil {
mIndex := rand.Int31n(int32(len(machineInfos)))
machine := machineInfos[mIndex]
if machine.M.Ip[0] == '_' {
fmt.Println("By ID")
binary.Write(conn, binary.LittleEndian, int16(machine.M.UniqueId))
}
for fI, field := range machine.Fields {
switch {
case field.FieldType == "INT":
switch {
case field.FieldSize == 2:
binary.Write(conn, binary.BigEndian, int16(1000+fI))
case field.FieldSize == 4:
binary.Write(conn, binary.BigEndian, int32(1000+fI))
}
}
}
time.Sleep(time.Duration(10+rand.Int31n(delay)) * time.Millisecond)
conn.Close()
} else {
fmt.Println("timeout")
}
channel <- 0
channelGoCount <- -1
}
示例3: TestCMSAccuracy
func TestCMSAccuracy(t *testing.T) {
seed := int64(7364181)
rand.Seed(seed)
msb := int32(20)
numItems := 1000000
items := make([]int32, numItems)
cms := streaming.MakeCMS(0.0001, 0.01, seed)
for i, _ := range items {
next_msb := uint32(rand.Int31n(msb))
items[i] = rand.Int31n(int32(1 << next_msb))
cms.Update(intToBuf(items[i]), float64(1))
}
actual := make([]int32, 1<<uint32(msb))
for _, x := range items {
actual[x] += 1
}
numErrors := 0
for item, cnt := range actual {
est, _ := cms.Count(intToBuf(int32(item)))
diff := math.Abs(est-float64(cnt)) / float64(numItems)
if diff > 1.0001 {
numErrors += 1
}
}
if errorRate := float64(numErrors) / float64(len(actual)); errorRate > 0.01 {
t.Errorf("errorRate %d > 0.01", errorRate)
}
}
示例4: TestRandomCaps
func TestRandomCaps(t *testing.T) {
rc := &RegionCoverer{}
for i := 0; i < 1000; i++ {
rc.MinLevel = int(rand.Int31n(maxLevel + 1))
rc.MaxLevel = int(rand.Int31n(maxLevel + 1))
for rc.MinLevel > rc.MaxLevel {
rc.MinLevel = int(rand.Int31n(maxLevel + 1))
rc.MaxLevel = int(rand.Int31n(maxLevel + 1))
}
rc.LevelMod = int(1 + rand.Int31n(3))
rc.MaxCells = int(skewedInt(10))
maxArea := math.Min(4*math.Pi, float64(3*rc.MaxCells+1)*AvgAreaMetric.Value(rc.MinLevel))
r := Region(randomCap(0.1*AvgAreaMetric.Value(rc.MaxLevel), maxArea))
covering := rc.Covering(r)
checkCovering(t, rc, &r, covering, false)
interior := rc.InteriorCovering(r)
checkCovering(t, rc, &r, interior, true)
// Check that Covering is deterministic.
covering2 := rc.Covering(r)
if !reflect.DeepEqual(covering, covering2) {
t.Errorf("Iteration %d, got covering = %v, want covering = %v", i, covering2, covering)
}
// Also check Denormalize. The denormalized covering
// may still be different and smaller than "covering" because
// s2.RegionCoverer does not guarantee that it will not output all four
// children of the same parent.
covering.Denormalize(rc.MinLevel, rc.LevelMod)
checkCovering(t, rc, &r, covering, false)
}
}
示例5: evaluate
func (self *Population) evaluate() {
for k := 0; k < self.conf.CrossoversCount; k++ {
if rand.Float64() < self.conf.CrossoverProb {
g1 := self.P[rand.Int31n(int32(math.Min(float64(len(self.P)), float64(self.conf.SelectionCount))))]
g2 := self.P[rand.Int31n(int32(math.Min(float64(len(self.P)), float64(self.conf.SelectionCount))))]
child := g1.Crossover(g2)
if rand.Float64() < self.conf.MutationProb {
child.Mutate()
}
child.EvalFitness()
self.P = append(self.P, child)
}
}
self.sort()
if self.conf.RemoveDuplicates {
self.removeDuplicates()
}
for i := range self.P {
self.P[i].EvalFitness()
}
if len(self.P) > self.conf.PopulationSize {
self.P = self.P[:self.conf.PopulationSize]
}
// pretty.Println(self.P)
}
示例6: runMVCCGet
// runMVCCGet first creates test data (and resets the benchmarking
// timer). It then performs b.N MVCCGets.
func runMVCCGet(emk engineMaker, numVersions, valueSize int, b *testing.B) {
const overhead = 48 // Per key/value overhead (empirically determined)
const targetSize = 512 << 20 // 512 MB
// Adjust the number of keys so that each test has approximately the same
// amount of data.
numKeys := targetSize / ((overhead + valueSize) * (1 + (numVersions-1)/2))
eng, _ := setupMVCCData(emk, numVersions, numKeys, valueSize, b)
defer eng.Close()
b.SetBytes(int64(valueSize))
b.ResetTimer()
keyBuf := append(make([]byte, 0, 64), []byte("key-")...)
for i := 0; i < b.N; i++ {
// Choose a random key to retrieve.
keyIdx := rand.Int31n(int32(numKeys))
key := roachpb.Key(encoding.EncodeUvarintAscending(keyBuf[:4], uint64(keyIdx)))
walltime := int64(5 * (rand.Int31n(int32(numVersions)) + 1))
ts := makeTS(walltime, 0)
if v, _, err := MVCCGet(context.Background(), eng, key, ts, true, nil); err != nil {
b.Fatalf("failed get: %s", err)
} else if v == nil {
b.Fatalf("failed get (key not found): %[email protected]%d", keyIdx, walltime)
} else if valueBytes, err := v.GetBytes(); err != nil {
b.Fatal(err)
} else if len(valueBytes) != valueSize {
b.Fatalf("unexpected value size: %d", len(valueBytes))
}
}
b.StopTimer()
}
示例7: BenchmarkInsertRR
// BenchmarkInsertRR *only* tests insertRR, not the taskRecord funcs.
func BenchmarkInsertRR(b *testing.B) {
const (
clusterSize = 1000
appCount = 5
)
var (
slaves = make([]string, clusterSize)
apps = make([]string, appCount)
rg = &RecordGenerator{
As: rrs{},
SRVs: rrs{},
}
)
for i := 0; i < clusterSize; i++ {
slaves[i] = "slave" + strconv.Itoa(i)
}
for i := 0; i < appCount; i++ {
apps[i] = "app" + strconv.Itoa(i)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
var (
si = rand.Int31n(clusterSize)
ai = rand.Int31n(appCount)
)
rg.insertRR(apps[ai], slaves[si], "A")
}
}
示例8: genValues
func genValues() {
for {
time.Sleep(time.Duration(rand.Int31n(1000)) * time.Millisecond)
value := int(rand.Int31n(10) + 1)
bi.AddValue(bi.Average, "average", value)
bi.AddValue(bi.Max, "max", value)
bi.AddValue(bi.Min, "min", value)
bi.AddValue(bi.Sum, "sum", value)
value = int(rand.Int31n(10) + 1)
bi.AddValue(bi.Average, "a.average", value)
bi.AddValue(bi.Max, "a.max", value)
bi.AddValue(bi.Min, "a.min", value)
bi.AddValue(bi.Sum, "a.sum", value)
value = int(rand.Int31n(10) + 1)
bi.AddValue(bi.Average, "a.b.average", value)
bi.AddValue(bi.Max, "a.b.max", value)
bi.AddValue(bi.Min, "a.c.min", value)
bi.AddValue(bi.Sum, "a.c.sum", value)
value = int(rand.Int31n(10) + 1)
bi.AddValue(bi.Average, "b.average", value)
bi.AddValue(bi.Max, "b.max", value)
bi.AddValue(bi.Min, "b.min", value)
bi.AddValue(bi.Sum, "b.sum", value)
}
}
示例9: TestMatchGeoIP
func TestMatchGeoIP(t *testing.T) {
if g4 == nil {
t.Skip("no geoip data")
}
matches := 0
hits := 0
for i := 0; i < N; i++ {
ips := fmt.Sprintf("%d.%d.%d.%d", rand.Int31n(256), rand.Int31n(256), rand.Int31n(256), rand.Int31n(256))
ip := net.ParseIP(ips)
if ip == nil {
panic("can't parse ip")
}
ccn := ipcc.Lookup(ip)
ccg, _ := g4.GetCountry(ips)
ccg = strings.ToLower(ccg)
if ccn == ccg {
matches++
if ccn != "" {
hits++
}
}
}
r := float32(matches) / N
t.Log(r, matches, hits)
if r < 0.9 {
t.Error("< 90% matches with geoip db")
}
}
示例10: TestRGBAToNRGBA
func TestRGBAToNRGBA(t *testing.T) {
test := func(r, g, b, a uint16) {
r1, g1, b1, a1 := RGBAToNRGBA(uint32(r), uint32(g), uint32(b), uint32(a))
c := color.NRGBA64Model.Convert(color.RGBA64{r, g, b, a}).(color.NRGBA64)
r2, g2, b2, a2 := uint32(c.R), uint32(c.G), uint32(c.B), uint32(c.A)
if r1 != r2 || g1 != g2 || b1 != b2 || a1 != a2 {
t.Errorf("different color: {%d %d %d %d}: got {%d %d %d %d}, want {%d %d %d %d}", r, g, b, a, r1, g1, b1, a1, r2, g2, b2, a2)
}
}
vals := []uint16{0, 0x4000, 0x8000, 0xc000, 0xffff}
for i, a := range vals {
for _, r := range vals[:i+1] {
for _, g := range vals[:i+1] {
for _, b := range vals[:i+1] {
test(r, g, b, a)
}
}
}
}
for i := 0; i < 1000; i++ {
a := uint16(rand.Int31n(1 << 16))
r := uint16(rand.Int31n(int32(a) + 1))
g := uint16(rand.Int31n(int32(a) + 1))
b := uint16(rand.Int31n(int32(a) + 1))
test(r, g, b, a)
}
}
示例11: main
func main() {
rand.Seed(time.Now().Unix())
port := flag.Int("port", 8081, "the port of the service")
ip := flag.String("bind", "127.0.0.1", "the ip of the service")
consumer := flag.String("consumer", "localhost:8070", "consumer hostname and 'admin' port")
flag.Parse()
fmt.Printf("Starting the flaky backend at port [%d]\n", *port)
ticker := time.NewTicker(5 * time.Second)
go func(ticker *time.Ticker) {
uri := fmt.Sprintf("http://%s/worker/%s:%d", *consumer, *ip, *port)
body := url.Values{}
for _ = range ticker.C {
http.PostForm(uri, body)
}
}(ticker)
a := gin.Default()
a.GET("/", func(c *gin.Context) {
fakeLoad()
if 90 < rand.Int31n(100) {
c.String(500, "Internal server error")
} else {
products := ""
for total := rand.Int31n(20); total > 0; total-- {
products += MakeProduct()
}
c.String(200, fmt.Sprintf("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<ProductList>%s\n</ProductList>", products))
}
})
a.Run(fmt.Sprintf(":%d", *port))
}
示例12: recv_packet
func (self *noisy_chan) recv_packet(p *network_packet) {
self.rx_count++
self.drop_count++ //pre increase
//drop by lose rate
if rand.Int31n(100) < int32(self.lose_rate) {
return
}
//drop by capacity
if self.capacity > 0 && self.packets.Len() >= self.capacity {
return
}
//drop by packet size
if self.max_packet_size > 0 && len(p.data) > self.max_packet_size {
return
}
self.drop_count-- //backoff
item := &nosiy_chan_item{p: p, queued_time: time.Now()}
//50% change of disorder
self.packets_mutex.Lock()
if self.disorder && rand.Int31n(100) < 50 && self.packets.Len() > 0 {
self.packets.InsertBefore(item, self.packets.Back())
} else {
self.packets.PushBack(item)
}
self.packets_mutex.Unlock()
self.send_cond.Signal()
}
示例13: runMVCCGet
// runMVCCGet first creates test data (and resets the benchmarking
// timer). It then performs b.N MVCCGets.
func runMVCCGet(numVersions int, b *testing.B) {
// Use the same number of keys for all of the mvcc get
// benchmarks. Using a different number of keys per test gives
// preferential treatment to tests with fewer keys. Note that the
// datasets all fit in cache and the cache is pre-warmed.
const numKeys = 100000
rocksdb := setupMVCCScanData(numVersions, numKeys, b)
defer rocksdb.Close()
prewarmCache(rocksdb)
b.SetBytes(1024)
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
keyBuf := append(make([]byte, 0, 64), []byte("key-")...)
for pb.Next() {
// Choose a random key to retrieve.
keyIdx := rand.Int31n(int32(numKeys))
key := proto.Key(encoding.EncodeUvarint(keyBuf[0:4], uint64(keyIdx)))
walltime := int64(5 * (rand.Int31n(int32(numVersions)) + 1))
ts := makeTS(walltime, 0)
if v, _, err := MVCCGet(rocksdb, key, ts, true, nil); err != nil {
b.Fatalf("failed get: %s", err)
} else if len(v.Bytes) != 1024 {
b.Fatalf("unexpected value size: %d", len(v.Bytes))
}
}
})
b.StopTimer()
}
示例14: randomHex
func randomHex() (value string) {
var length = rand.Int31n(10) + 5
for x := int32(0); x < length; x += 1 {
value = fmt.Sprintf("%s%02x", value, rand.Int31n(256))
}
return
}
示例15: test_2
func test_2() {
const pauseSec time.Duration = 5
ansiterm.ClearPage()
ansiterm.MoveToRC(9, 20)
fmt.Printf("In a few seconds program will print 1000 X chars")
ansiterm.MoveToRC(10, 20)
fmt.Printf("This is slowed by forcing a 10 ms sleep per loop")
pause(pauseSec)
ansiterm.ClearPage()
for i := 0; i < 1000; i++ {
row := int(rand.Int31n(25))
col := int(rand.Int31n(80))
ansiterm.MoveToRC(row, col)
time.Sleep(time.Duration(0.01 * float64(time.Second)))
fmt.Printf("X")
}
pause(pauseSec)
ansiterm.ClearPage()
ansiterm.MoveToRC(9, 20)
fmt.Printf("In a few seconds program will print 1000 X chars")
ansiterm.MoveToRC(10, 20)
fmt.Printf("using the same program at FULL speed - don't blink...")
pause(pauseSec)
ansiterm.ClearPage()
for i := 0; i < 1000; i++ {
row := int(rand.Int31n(25))
col := int(rand.Int31n(80))
ansiterm.MoveToRC(row, col)
fmt.Printf("X")
}
pause(pauseSec)
ansiterm.ClearPage()
}