本文整理汇总了Golang中math/rand.Intn函数的典型用法代码示例。如果您正苦于以下问题:Golang Intn函数的具体用法?Golang Intn怎么用?Golang Intn使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Intn函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Run
func (h *ikr) Run(res *hal.Response) error {
now := time.Now()
rand.Seed(int64(now.Unix()))
//only fire half the time
if rand.Intn(100) >= 50 {
return nil
}
replies := []string{
"*I know right?!*",
"*OMG* couldn't agree more",
":+1:",
"+1",
":arrow_up: THAT",
":arrow_up: you complete me :arrow_up:",
"so true",
"agreed.",
"that's the fact jack",
"YUUUUUUP",
"that's what I'm talkin bout",
"*IKR?!*",
"singit",
"^droppin the truth bombs :boom: :boom: :boom:",
"#legit",
"/me nodds emphatically in agreement",
"for REALZ though",
"FOR REALSIES",
"it's like you *literally* just read my mind right now",
}
reply := replies[rand.Intn(len(replies)-1)]
hal.Logger.Debug(" *** ikr:Sending response: %s", reply)
res.Send(reply)
return nil
}
示例2: rnd
func rnd() (sz []int) {
sz = make([]int, rand.Intn(8)+1)
for i := range sz {
sz[i] = rand.Intn(10) + 1
}
return
}
示例3: initRand
// Initialize entities to random variables in order to test ledger status consensus
func (t *SimpleChaincode) initRand(stub *shim.ChaincodeStub, args []string) ([]byte, error) {
var A, B string // Entities
var Aval, Bval int // Asset holdings
var err error
if len(args) != 4 {
return nil, errors.New("Incorrect number of arguments. Expecting 4")
}
// Initialize the chaincode
A = args[0]
Aval = rand.Intn(100)
B = args[1]
Bval = rand.Intn(100)
fmt.Printf("Aval = %d, Bval = %d\n", Aval, Bval)
// Write the state to the ledger
err = stub.PutState(A, []byte(strconv.Itoa(Aval)))
if err != nil {
return nil, err
}
err = stub.PutState(B, []byte(strconv.Itoa(Bval)))
if err != nil {
return nil, err
}
return nil, nil
}
示例4: TestLXCConfig
func TestLXCConfig(t *testing.T) {
runtime := mkRuntime(t)
defer nuke(runtime)
// Memory is allocated randomly for testing
rand.Seed(time.Now().UTC().UnixNano())
memMin := 33554432
memMax := 536870912
mem := memMin + rand.Intn(memMax-memMin)
// CPU shares as well
cpuMin := 100
cpuMax := 10000
cpu := cpuMin + rand.Intn(cpuMax-cpuMin)
container, err := runtime.Create(&Config{
Image: GetTestImage(runtime).ID,
Cmd: []string{"/bin/true"},
Hostname: "foobar",
Memory: int64(mem),
CpuShares: int64(cpu),
},
)
if err != nil {
t.Fatal(err)
}
defer runtime.Destroy(container)
container.generateLXCConfig(nil)
grepFile(t, container.lxcConfigPath(), "lxc.utsname = foobar")
grepFile(t, container.lxcConfigPath(),
fmt.Sprintf("lxc.cgroup.memory.limit_in_bytes = %d", mem))
grepFile(t, container.lxcConfigPath(),
fmt.Sprintf("lxc.cgroup.memory.memsw.limit_in_bytes = %d", mem*2))
}
示例5: OnTick
func (t1 *Test1) OnTick(account *accounts.Account, exchange *exchanges.Exchange, tick *ticks.Tick, vars *variables.Variables) {
for _, trade := range account.OpenTrades() {
someCriteria := true
if someCriteria {
exchange.CloseTrade(account, trade, tick)
}
return
}
lower := vars.GetFloat("ma_crossover_threshold_lower")
upper := vars.GetFloat("ma_crossover_threshold_upper")
currentCrossover := 1.23
lots := 1.0
stopLoss := 25.0
takeProfit := 50.0
if 0 == rand.Intn(1000) || currentCrossover > lower && currentCrossover < upper {
if 0 == rand.Intn(2) {
exchange.OpenLong(account, tick, lots, stopLoss, takeProfit)
} else {
exchange.OpenShort(account, tick, lots, stopLoss, takeProfit)
}
}
}
示例6: NewBullet
func NewBullet(boundary *gt2d.Rectangle) *Bullet {
rand.Seed(time.Now().UTC().UnixNano())
bullet := new(Bullet)
bullet.Boundary = boundary
// init with a random velocity and direction
bullet.Velocity = new(gt2d.Vector2D)
for {
if abs(bullet.Velocity.X) > 1 && abs(bullet.Velocity.Y) > 1 {
break
}
bullet.Velocity.X = rand.Intn(16) - 8
bullet.Velocity.Y = rand.Intn(16) - 8
}
bullet.CurrentPosition = new(gt2d.Vector2D)
bullet.LastPosition = new(gt2d.Vector2D)
bullet.CurrentPosition.X = boundary.Width() / 2
bullet.CurrentPosition.Y = boundary.Height() / 2
bullet.LastPosition.X = bullet.CurrentPosition.X
bullet.LastPosition.Y = bullet.CurrentPosition.Y
bullet.Rect = gt2d.Rect(bullet.CurrentPosition.X-5, bullet.CurrentPosition.Y-5, bullet.CurrentPosition.X+5, bullet.CurrentPosition.Y+5)
return bullet
}
示例7: BenchmarkAddAndQueryPost
func BenchmarkAddAndQueryPost(b *testing.B) {
// Pre-build posts and queries so we're not measuring that.
rand := rand.New(rand.NewSource(time.Now().UnixNano()))
idx := &PostIndex{}
posts := createPosts(aliceChain, 100000, rand) // Large number of posts to query
for _, v := range posts {
idx.AddPost(v.id, v.words)
}
posts = createPosts(aliceChain, b.N, rand) // New posts!
queries := make([]string, b.N)
for i := 0; i < len(queries); i++ {
ql := rand.Intn(4) + 1
t := aliceChain.Generate(ql, rand)
w := splitToWords(t)
queries[i] = randomQuery(w, rand)
}
var index int32 = -1 // Count up to N but atomically
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
i := atomic.AddInt32(&index, 1)
if rand.Intn(5) == 0 {
p := posts[i]
idx.AddPost(p.id, p.words)
} else {
q := queries[i]
idx.QueryPosts(q, 100)
}
}
})
}
示例8: BenchmarkParallelUdpParse
// Benchmark that runs with parallelism to help find concurrency related
// issues. To run with parallelism, the 'go test' cpu flag must be set
// greater than 1, otherwise it just runs concurrently but not in parallel.
func BenchmarkParallelUdpParse(b *testing.B) {
rand.Seed(22)
numMessages := len(messages)
dns := newDNS(false)
client := dns.results.(*publish.ChanTransactions)
// Drain the results channal while the test is running.
go func() {
totalMessages := 0
for r := range client.Channel {
_ = r
totalMessages++
}
fmt.Printf("Parsed %d messages.\n", totalMessages)
}()
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
// Each iteration parses one message, either a request or a response.
// The request and response could be parsed on different goroutines.
for pb.Next() {
q := messages[rand.Intn(numMessages)]
var packet *protos.Packet
if rand.Intn(2) == 0 {
packet = newPacket(forward, q.request)
} else {
packet = newPacket(reverse, q.response)
}
dns.ParseUDP(packet)
}
})
defer close(client.Channel)
}
示例9: createImage
func createImage(iterations uint32, degree float64, factor float64) {
// Declare image size
width, height := 2048, 1024
// Create a new image
img := image.Rect(0, 0, width, height)
c := NewCanvas(img)
c.DrawGradient()
rand.Seed(time.Now().UTC().UnixNano())
for i := 0; i < 300; i++ {
x := float64(width) * rand.Float64()
y := float64(height) * rand.Float64()
color := color.RGBA{uint8(rand.Intn(255)),
uint8(rand.Intn(255)),
uint8(rand.Intn(255)),
255}
c.DrawSpiral(color, Coordinate{x, y}, iterations, degree, factor)
}
name := fmt.Sprintf("spiral_%d_%f_%f.png", iterations, degree, factor)
file, err := os.Create(name)
if err != nil {
log.Fatal(err)
}
defer file.Close()
png.Encode(file, c)
}
示例10: generateOneFile
func generateOneFile(fd io.ReadSeeker, p1 string, s int64) error {
src := io.LimitReader(&inifiteReader{fd}, int64(s))
dst, err := os.Create(p1)
if err != nil {
return err
}
_, err = io.Copy(dst, src)
if err != nil {
return err
}
err = dst.Close()
if err != nil {
return err
}
_ = os.Chmod(p1, os.FileMode(rand.Intn(0777)|0400))
t := time.Now().Add(-time.Duration(rand.Intn(30*86400)) * time.Second)
err = os.Chtimes(p1, t, t)
if err != nil {
return err
}
return nil
}
示例11: TestList
// TestList checks the returned list of keys after populating a directory tree.
func (suite *DriverSuite) TestList(c *check.C) {
rootDirectory := "/" + randomFilename(int64(8+rand.Intn(8)))
defer suite.StorageDriver.Delete(rootDirectory)
parentDirectory := rootDirectory + "/" + randomFilename(int64(8+rand.Intn(8)))
childFiles := make([]string, 50)
for i := 0; i < len(childFiles); i++ {
childFile := parentDirectory + "/" + randomFilename(int64(8+rand.Intn(8)))
childFiles[i] = childFile
err := suite.StorageDriver.PutContent(childFile, randomContents(32))
c.Assert(err, check.IsNil)
}
sort.Strings(childFiles)
keys, err := suite.StorageDriver.List("/")
c.Assert(err, check.IsNil)
c.Assert(keys, check.DeepEquals, []string{rootDirectory})
keys, err = suite.StorageDriver.List(rootDirectory)
c.Assert(err, check.IsNil)
c.Assert(keys, check.DeepEquals, []string{parentDirectory})
keys, err = suite.StorageDriver.List(parentDirectory)
c.Assert(err, check.IsNil)
sort.Strings(keys)
c.Assert(keys, check.DeepEquals, childFiles)
// A few checks to add here (check out #819 for more discussion on this):
// 1. Ensure that all paths are absolute.
// 2. Ensure that listings only include direct children.
// 3. Ensure that we only respond to directory listings that end with a slash (maybe?).
}
示例12: checkWinOrAdd
/* 检查游戏是否已经胜利,没有胜利的情况下随机将值为0的元素
*随机设置为2或者4
*/
func (t *G4096) checkWinOrAdd() Status2 {
// 判断4x4中是否有元素的值大于(等于)4096,有则获胜利
for _, x := range t {
for _, y := range x {
if y >= Max2 {
return Win2
}
}
}
// 开始随机设置零值元素为2或者4
i := rand.Intn(len(t))
j := rand.Intn(len(t))
for x := 0; x < len(t); x++ {
for y := 0; y < len(t); y++ {
if t[i%len(t)][j%len(t)] == 0 {
t[i%len(t)][j%len(t)] = 2 << (rand.Uint32() % 2)
return Add2
}
j++
}
i++
}
// 全部元素都不为零(表示已满),则失败
return Lose2
}
示例13: randomFile
func randomFile(d *Directory) (*File, error) {
d, err := randomWalk(d, rand.Intn(6))
if err != nil {
return nil, err
}
ents, err := d.List()
if err != nil {
return nil, err
}
var files []string
for _, e := range ents {
if e.Type == int(TFile) {
files = append(files, e.Name)
}
}
if len(files) == 0 {
return nil, nil
}
fname := files[rand.Intn(len(files))]
fsn, err := d.Child(fname)
if err != nil {
return nil, err
}
fi, ok := fsn.(*File)
if !ok {
return nil, errors.New("file wasnt a file, race?")
}
return fi, nil
}
示例14: actorMakeFile
func actorMakeFile(d *Directory) error {
d, err := randomWalk(d, rand.Intn(7))
if err != nil {
return err
}
name := randomName()
f, err := NewFile(name, &dag.Node{Data: ft.FilePBData(nil, 0)}, d, d.dserv)
if err != nil {
return err
}
wfd, err := f.Open(OpenWriteOnly, true)
if err != nil {
return err
}
r := io.LimitReader(randbo.New(), int64(77*rand.Intn(123)))
_, err = io.Copy(wfd, r)
if err != nil {
return err
}
err = wfd.Close()
if err != nil {
return err
}
return nil
}
示例15: NewImage
func NewImage(digits []byte, width, height int) *Image {
img := new(Image)
r := image.Rect(img.width, img.height, stdWidth, stdHeight)
img.NRGBA = image.NewNRGBA(r)
img.color = &color.NRGBA{
uint8(rand.Intn(129)),
uint8(rand.Intn(129)),
uint8(rand.Intn(129)),
0xFF,
}
// Draw background (10 random circles of random brightness)
img.calculateSizes(width, height, len(digits))
img.fillWithCircles(10, img.dotsize)
maxx := width - (img.width+img.dotsize)*len(digits) - img.dotsize
maxy := height - img.height - img.dotsize*2
x := rnd(img.dotsize*2, maxx)
y := rnd(img.dotsize*2, maxy)
// Draw digits.
for _, n := range digits {
img.drawDigit(font[n], x, y)
x += img.width + img.dotsize
}
// Draw strike-through line.
img.strikeThrough()
return img
}