当前位置: 首页>>代码示例>>Golang>>正文


Golang rand.Int函数代码示例

本文整理汇总了Golang中math/rand.Int函数的典型用法代码示例。如果您正苦于以下问题:Golang Int函数的具体用法?Golang Int怎么用?Golang Int使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Int函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: TestBasic

func TestBasic(t *testing.T) {
	smh, gids, ha, _, clean := setup("basic", false)
	defer clean()

	fmt.Printf("Test: Basic Join/Leave ...\n")

	mck := shardmaster.MakeClerk(smh)
	mck.Join(gids[0], ha[0])

	ck := MakeClerk(smh)

	ck.Put("a", "x")
	v := ck.PutHash("a", "b")
	if v != "x" {
		t.Fatalf("Puthash got wrong value")
	}
	ov := NextValue("x", "b")
	if ck.Get("a") != ov {
		t.Fatalf("Get got wrong value")
	}

	keys := make([]string, 10)
	vals := make([]string, len(keys))
	for i := 0; i < len(keys); i++ {
		keys[i] = strconv.Itoa(rand.Int())
		vals[i] = strconv.Itoa(rand.Int())
		ck.Put(keys[i], vals[i])
	}
	// are keys still there after joins?
	for g := 1; g < len(gids); g++ {
		mck.Join(gids[g], ha[g])
		time.Sleep(1 * time.Second)
		for i := 0; i < len(keys); i++ {
			v := ck.Get(keys[i])
			if v != vals[i] {
				t.Fatalf("joining; wrong value; g=%v k=%v wanted=%v got=%v",
					g, keys[i], vals[i], v)
			}
			vals[i] = strconv.Itoa(rand.Int())
			ck.Put(keys[i], vals[i])
		}
	}

	// are keys still there after leaves?
	for g := 0; g < len(gids)-1; g++ {
		mck.Leave(gids[g])
		time.Sleep(1 * time.Second)
		for i := 0; i < len(keys); i++ {
			v := ck.Get(keys[i])
			if v != vals[i] {
				t.Fatalf("leaving; wrong value; g=%v k=%v wanted=%v got=%v",
					g, keys[i], vals[i], v)
			}
			vals[i] = strconv.Itoa(rand.Int())
			ck.Put(keys[i], vals[i])
		}
	}

	fmt.Printf("  ... Passed\n")
}
开发者ID:bohaoist,项目名称:mit-6.824-distributed-system-2014spring,代码行数:60,代码来源:test_test.go

示例2: newResult

func newResult(q quiz) result {
	r := result{
		Level:    q.Level,
		End:      q.Start.Add(q.Duration),
		Duration: q.Duration,
		Word:     q.Word,
		Tries:    q.Tries,
	}
	t := r.End.Unix()
	r.ID = []byte{
		byte(t >> 56),
		byte(t >> 48),
		byte(t >> 40),
		byte(t >> 32),
		byte(t >> 24),
		byte(t >> 16),
		byte(t >> 8),
		byte(t),
		byte(rand.Int()),
		byte(rand.Int()),
		byte(rand.Int()),
		byte(rand.Int()),
	}

	return r
}
开发者ID:kalafut,项目名称:gmw,代码行数:26,代码来源:leaderboard.go

示例3: TestHDel

func TestHDel(t *testing.T) {
	ss := []string{}
	for i := 0; i < 32; i++ {
		k := strconv.Itoa(i)
		v := strconv.Itoa(rand.Int())
		ss = append(ss, k, v)
	}
	hmset(t, 0, "hash", ss...)
	hgetall(t, 0, "hash", ss...)

	hdel(t, 0, "hash", 2, "0", "1")
	hdel(t, 0, "hash", 1, "2", "2", "2")
	hdel(t, 0, "hash", 0, "0", "1", "2", "0", "1", "2")

	hlen(t, 0, "hash", int64(len(ss)/2)-3)
	hgetall(t, 0, "hash", ss[6:]...)
	kpexpire(t, 0, "hash", 10, 1)
	sleepms(20)
	hdelall(t, 0, "hash", 0)

	for i := 0; i < 10; i++ {
		hset(t, 0, "hash", strconv.Itoa(i), strconv.Itoa(rand.Int()), 1)
	}
	for i := 0; i < 10; i++ {
		hdel(t, 0, "hash", 1, strconv.Itoa(i))
		hdel(t, 0, "hash", 0, strconv.Itoa(i))
	}
	hgetall(t, 0, "hash")
	checkempty(t)
}
开发者ID:fengshao0907,项目名称:rpdb,代码行数:30,代码来源:hash_test.go

示例4: TestSearchBig

func TestSearchBig(t *testing.T) {

	if testing.Short() {
		t.Skip("Skipping big test search")
	}

	rand.Seed(0)

	const maxLimit = 100e6

	ints := make([]int, maxLimit)

	for i := 0; i < maxLimit; i++ {
		ints[i] = rand.Int()
	}

	sort.Ints(ints)

	for i := 0; i < 100000000; i++ {
		elt := rand.Int()
		vidx := Search(ints, elt)
		idx := sort.SearchInts(ints, elt)
		if vidx != idx {
			t.Fatalf("Search failed for elt=%d: got %d want %d\n", elt, vidx, idx)
		}
	}
}
开发者ID:KanwarGill,项目名称:trifles,代码行数:27,代码来源:interp_test.go

示例5: benchZRevRangeByScore

func benchZRevRangeByScore() {
	f := func() {
		waitBench("zrevrangebyscore", "myzsetkey", 0, rand.Int(), "withscores", "limit", rand.Int()%100, 100)
	}

	bench("zrevrangebyscore", f)
}
开发者ID:Eddie0330,项目名称:ledisdb,代码行数:7,代码来源:main.go

示例6: Do

func (c *Client) Do(req *http.Request) (*http.Response, error) {
	if strings.HasPrefix(c.Key, "jwt:") {
		req.Header.Add("Authorization", strings.Split(c.Key, ":")[1])
	}
	req.Header.Set("User-Agent", c.UserAgent)

	var res *http.Response
	var err error

	retryPatterns := append(c.RetryPatterns, time.Millisecond)

	for _, sleepTime := range retryPatterns {
		res, err = c.HTTPClient.Do(req)
		if err != nil {
			if strings.Contains(err.Error(), "TLS handshake timeout") {
				time.Sleep(sleepTime + time.Duration(rand.Int()%1000)*time.Millisecond)
				continue
			}
			return nil, err
		}

		if res.StatusCode == 503 {
			// Rate limited, try again according to patterns.
			// following https://cloud.google.com/storage/docs/json_api/v1/how-tos/upload#exp-backoff to the letter
			res.Body.Close()
			time.Sleep(sleepTime + time.Duration(rand.Int()%1000)*time.Millisecond)
			continue
		}

		break
	}

	return res, err
}
开发者ID:itchio,项目名称:butler,代码行数:34,代码来源:itchio.go

示例7: BenchmarkReadPid

func BenchmarkReadPid(b *testing.B) {
	b.StopTimer()
	c := new(Context)

	rand.Seed(time.Now().UnixNano())
	max := 64
	length := 16
	pids := make([]*bytes.Buffer, max)

	for i := 0; i < max; i++ {
		w := new(bytes.Buffer)
		s := bytes.Repeat([]byte{'a'}, length)
		b := bytes.Map(randRune, s)
		b[6] = '@'
		w.Write([]byte{ettPid, ettSmallAtom, byte(length)})
		w.Write(b)
		w.Write([]byte{0, 0, 0, uint8(rand.Int())})
		w.Write([]byte{0, 0, 0, uint8(rand.Int())})
		w.Write([]byte{uint8(rand.Int())})
		pids[i] = w
	}

	b.StartTimer()

	for i := 0; i < b.N; i++ {
		in := pids[i%max]
		_, err := c.Read(in)

		if err != io.EOF && err != nil {
			b.Fatal(err)
		}
	}
}
开发者ID:agelin,项目名称:etf,代码行数:33,代码来源:read_b_test.go

示例8: TestSetwinsz

// TestSetwinsz Tests settig the terminal windowsize
func TestSetwinsz(t *testing.T) {
	nf, err := donormfile("TestSetwinsz")
	if err != nil {
		t.Fatal("TestSetwinsz Could not create testfile, err: ", err)
	}
	defer nf.Close()
	wz = &tios.Wz
	var i, y uint16
	for i = 0; i < NUMTEST; i++ {
		for y = 0; y < NUMTEST; y++ {
			wz.WsRow = i
			wz.WsCol = y
			wz.WsXpixel = uint16(rand.Int())
			wz.WsYpixel = uint16(rand.Int())
			xp, yp := wz.WsXpixel, wz.WsYpixel
			if err = tios.Setwinsz(pty.Slave); err != nil {
				t.Errorf("Setwinsz could not set row: %d col: %d err: %v", i, y, err)
				t.Errorf("Setwinsz could not set x: %d y: %d err: %v", xp, yp, err)
			}
			if err = tios.Winsz(pty.Slave); err != nil {
				t.Error("Winsz failed: ", err)
			}
			if !(wz.WsRow == i && wz.WsCol == y && wz.WsXpixel == xp && wz.WsYpixel == yp) {
				t.Errorf("Setwinsz got row: %d col: %d want row: %d col: %d", i, y, wz.WsRow, wz.WsCol)
				t.Errorf("Setwinsz got x: %d y: %d want x: %d y: %d", xp, yp, wz.WsXpixel, wz.WsYpixel)
			}
		}
	}
	if err = tios.Setwinsz(nf); err == nil {
		t.Error("Setwinsz should not work for std. file")
	}
}
开发者ID:postfix,项目名称:goterm-1,代码行数:33,代码来源:termios_test.go

示例9: TestChecksum

func TestChecksum(t *testing.T) {
	// Test even-size checksum
	buf := make([]byte, 2+40)
	for i := 2; i < len(buf); i++ {
		buf[i] = byte(rand.Int())
	}
	csumUint16ToBytes(
		csumDone(csumSum(buf)),
		buf[0:2],
	)
	if csumDone(csumSum(buf)) != 0 {
		t.Errorf("csum")
	}

	// Test odd-size checksum
	buf = make([]byte, 41+2)
	for i := 2; i < len(buf); i++ {
		buf[i] = byte(rand.Int())
	}
	csumUint16ToBytes(
		csumDone(csumSum(buf)),
		buf[0:2],
	)
	if csumDone(csumSum(buf)) != 0 {
		t.Errorf("csum")
	}

}
开发者ID:hashken,项目名称:GoDCCP,代码行数:28,代码来源:checksum_test.go

示例10: Create

func (i *chunkRecord) Create(file string) (count int64, err error) {
	tmpFilePath := fmt.Sprintf("%s/temp/%d%d.idx", conf.Conf["data-path"], rand.Int(), rand.Int())

	f, err := os.Create(tmpFilePath)
	if err != nil {
		return
	}
	defer f.Close()

	curr := int64(0)
	count = 0
	for {
		n, er := i.r.SeekChunk(curr)
		if er != nil {
			if er != io.EOF {
				err = er
				return
			}
			binary.Write(f, binary.LittleEndian, curr)
			binary.Write(f, binary.LittleEndian, i.size-curr)
			count += 1
			break
		} else {
			binary.Write(f, binary.LittleEndian, curr)
			binary.Write(f, binary.LittleEndian, n)
			curr += int64(n)
			count += 1
		}
	}
	err = os.Rename(tmpFilePath, file)

	return
}
开发者ID:narayandesai,项目名称:Shock,代码行数:33,代码来源:chunkrecord.go

示例11: mixedArray

func mixedArray(size int) []int32 {
	var list = make([]int32, size)

	const bits_of_int = uint(unsafe.Sizeof(list[0])) * 8
	var tmp = uint(size)
	var cnt uint = 0
	for cnt < bits_of_int && tmp != 0 {
		cnt++
		tmp >>= 1
	}
	cnt = bits_of_int - cnt - 11
	var mask = ^((^0) << cnt)

	var num = int32(0)
	rand.Seed(time.Now().Unix())
	for i := 0; i < size; i++ {
		if i%32 == 0 { //局部摻入有序数列
			num += int32(rand.Int() & mask)
			list[i] = num
		} else {
			list[i] = int32(rand.Int())
		}
	}
	return list
}
开发者ID:elvizlai,项目名称:DSGO,代码行数:25,代码来源:bench.go

示例12: testInt

func testInt(t *testing.T, n int) {
	values := make([]int, n)
	for i := range values {
		if i%2 == 0 {
			values[i] = rand.Int()
		} else {
			values[i] = -rand.Int()
		}
	}

	var buf bytes.Buffer
	w := bit.NewWriter(&buf)
	for _, v := range values {
		WriteInt(w, v)
	}

	err := w.Close()
	if err != nil {
		t.Errorf("w.Close: %v", err)
		return
	}

	r := bit.NewReader(&buf)
	for i, exp := range values {
		got, err := ReadInt(r), r.Error()
		if err != nil {
			t.Errorf("ReadInt: %v", err)
			return
		}
		if got != exp {
			t.Errorf("%v: %d got %v expected %v", values, i, got, exp)
			return
		}
	}
}
开发者ID:samuell,项目名称:exp,代码行数:35,代码来源:golomb_test.go

示例13: doit

func doit(name string) bool {
	if os.Getenv("GOSSAHASH") == "" {
		// Default behavior is yes.
		return true
	}
	// Check the hash of the name against a partial input hash.
	// We use this feature to do a binary search within a
	// package to find a function that is incorrectly compiled.
	hstr := ""
	for _, b := range sha1.Sum([]byte(name)) {
		hstr += fmt.Sprintf("%08b", b)
	}
	if strings.HasSuffix(hstr, os.Getenv("GOSSAHASH")) {
		for i := 7 & rand.Int(); i >= 0; i-- {
			fmt.Printf("GOSSAHASH triggered %s\n", name)
		}
		return true
	}
	// Iteratively try additional hashes to allow tests for
	// multi-point failure.
	for i := 0; true; i++ {
		ev := fmt.Sprintf("GOSSAHASH%d", i)
		evv := os.Getenv(ev)
		if evv == "" {
			break
		}
		if strings.HasSuffix(hstr, evv) {
			for i := 7 & rand.Int(); i >= 0; i-- {
				fmt.Printf("%s triggered %s\n", ev, name)
			}
			return true
		}
	}
	return false
}
开发者ID:dr2chase,项目名称:gossahash,代码行数:35,代码来源:fail.go

示例14: TestSlotNum

func TestSlotNum(t *testing.T) {
	tests := [][]string{
		[]string{"", ""},
		[]string{"{", "{"},
		[]string{"{test", "{test"},
		[]string{"{test{0}", "test{0"},
		[]string{"test{a}", "a"},
		[]string{"{b}test", "b"},
		[]string{"}test{c}", "c"},
		[]string{"}test", "}test"},
		[]string{"}test1{test2{d}}{e}", "test2{d"},
	}
	for _, p := range tests {
		key, tag := []byte(p[0]), []byte(p[1])
		checkerror(t, nil, bytes.Equal(HashTag(key), tag))
	}
	const n = MaxSlotNum * 32
	for i := 0; i < n; i++ {
		key := []byte(fmt.Sprintf("key_%d_%d", rand.Int(), rand.Int()))
		checkerror(t, nil, bytes.Equal(HashTag(key), key))
	}
	for i := 0; i < n; i++ {
		v := rand.Int()
		tag := []byte(fmt.Sprintf("%d", v))
		key := []byte(fmt.Sprintf("key_{%d}_%d", v, rand.Int()))
		checkerror(t, nil, bytes.Equal(HashTag(key), tag))
	}
}
开发者ID:fengshao0907,项目名称:rpdb,代码行数:28,代码来源:slots_test.go

示例15: DataUpload

// helper function to create a node from an http data post
func DataUpload(r *http.Request) (params map[string]string, files node.FormFiles, err error) {
	params = make(map[string]string)
	files = make(node.FormFiles)
	tmpPath := fmt.Sprintf("%s/temp/%d%d", conf.Conf["data-path"], rand.Int(), rand.Int())

	files["upload"] = node.FormFile{Name: "filename", Path: tmpPath, Checksum: make(map[string]string)}
	if tmpFile, err := os.Create(tmpPath); err == nil {
		defer tmpFile.Close()
		md5c := make(chan checkSumCom)
		writeChecksum(md5.New, md5c)
		for {
			buffer := make([]byte, 32*1024)
			n, err := r.Body.Read(buffer)
			if n == 0 || err != nil {
				md5c <- checkSumCom{n: 0}
				break
			}
			md5c <- checkSumCom{buf: buffer[0:n], n: n}
			tmpFile.Write(buffer[0:n])
		}
		md5r := <-md5c
		files["upload"].Checksum["md5"] = md5r.checksum
	} else {
		return nil, nil, err
	}

	return
}
开发者ID:paczian,项目名称:Shock,代码行数:29,代码来源:request.go


注:本文中的math/rand.Int函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。