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


Golang Rand.Intn方法代码示例

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


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

示例1: testRandomSimplex

func testRandomSimplex(t *testing.T, nTest int, pZero float64, maxN int, rnd *rand.Rand) {
	// Try a bunch of random LPs
	for i := 0; i < nTest; i++ {
		n := rnd.Intn(maxN) + 2 // n must be at least two.
		m := rnd.Intn(n-1) + 1  // m must be between 1 and n
		if m == 0 || n == 0 {
			continue
		}
		randValue := func() float64 {
			//var pZero float64
			v := rnd.Float64()
			if v < pZero {
				return 0
			}
			return rnd.NormFloat64()
		}
		a := mat64.NewDense(m, n, nil)
		for i := 0; i < m; i++ {
			for j := 0; j < n; j++ {
				a.Set(i, j, randValue())
			}
		}
		b := make([]float64, m)
		for i := range b {
			b[i] = randValue()
		}

		c := make([]float64, n)
		for i := range c {
			c[i] = randValue()
		}

		testSimplex(t, nil, c, a, b, convergenceTol)
	}
}
开发者ID:sbinet,项目名称:gonum-optimize,代码行数:35,代码来源:simplex_test.go

示例2: makedata

func makedata(minsize int, dice *rand.Rand) string {
	b := make([]rune, minsize+dice.Intn(minsize))
	for i := range b {
		b[i] = letters[dice.Intn(len(letters))]
	}
	return string(b)
}
开发者ID:mdmarek,项目名称:grid,代码行数:7,代码来源:datamaker.go

示例3: throw

func throw(g *rand.Rand, edge_amount, throws_amount int) int {
	var result int = 0
	for i := 0; i < throws_amount; i++ {
		result += g.Intn(edge_amount) + 1
	}
	return result
}
开发者ID:apanasenko,项目名称:MonsterQuest,代码行数:7,代码来源:dice.go

示例4: randomMemory

func randomMemory(rng *rand.Rand) *MemoryRegion {
	var mr *MemoryRegion
	var err error
	options := 3
	if tmpfsBuf != nil && hugeBuf != nil {
		options += 2
	}
	switch rng.Intn(options) {
	case 0:
		mr, err = AllocateMemory(4096)
	case 1:
		mr, err = AllocateMemory(65536)
	case 2:
		mr, err = AllocateMemory(1048576)
	case 3:
		mr, err = RegisterMemory(tmpfsBuf.Bytes())
	case 4:
		mr, err = RegisterMemory(hugeBuf.Bytes())
	default:
		panic("invalid mode")
	}
	if err != nil {
		panic(err)
	}
	return mr
}
开发者ID:hpdvanwyk,项目名称:ib,代码行数:26,代码来源:conn_test.go

示例5: RandomString

// There are lots of ways of doing this faster, but this is good
// enough.
func RandomString(rng *rand.Rand, size int) string {
	out := make([]byte, size)
	for i := 0; i < size; i++ {
		out[i] = alphabet[rng.Intn(size)]
	}
	return string(out)
}
开发者ID:WIZARD-CXY,项目名称:golang-devops-stuff,代码行数:9,代码来源:random.go

示例6: Shuffle

// iterate through the deck, and swap values with
// a random card from another location in the deck
func (sd *StandardDeck) Shuffle(r *rand.Rand) {
	s := sd.Size()
	for k := range sd.cards {
		i := r.Intn(s)
		sd.cards[k], sd.cards[i] = sd.cards[i], sd.cards[k]
	}
}
开发者ID:stensonb,项目名称:blackjack,代码行数:9,代码来源:standarddeck.go

示例7: GenerateSlice

func (c *STChain) GenerateSlice(max int, r *rand.Rand) []string {
	var s []string
	var p STPrefix

	for i := 0; i < max; i++ {
		suffix := c.Chain[p]
		if suffix.Count == 0 {
			return s
		}

		j := r.Intn(suffix.Count)

		for word, freq := range suffix.Words {
			j -= freq
			if j < 0 {
				if word == 0 {
					return s
				}

				p.shift(word)
				s = append(s, c.Strings[word])
			}
		}
	}

	return s
}
开发者ID:Nightgunner5,项目名称:markov,代码行数:27,代码来源:stringtable_markov.go

示例8: NextCall

func (ss *SessionScenario) NextCall(rg *rand.Rand) (*Call, error) {
	for {
		if i := rg.Intn(ss.SessionAmount); i >= 0 {
			select {
			case st := <-ss._sessions[i].StepLock:
				switch st {
				case STEP1:
					if ss._sessions[i]._calls[st].GenParam != nil {
						ss._sessions[i]._calls[st].Method, ss._sessions[i]._calls[st].Type, ss._sessions[i]._calls[st].URL, ss._sessions[i]._calls[st].Body = ss._sessions[i]._calls[st].GenParam()
					}
					// execute session call for the first time
					return ss._sessions[i]._calls[st], nil
				default:
					// choose a non-initialized call randomly
					ss._sessions[i].StepLock <- REST
					q := rg.Float32() * ss._sessions[i]._totalWeight
					for j := STEP1 + 1; j < ss._sessions[i]._count; j++ {
						if q <= ss._sessions[i]._calls[j].RandomWeight {
							if ss._sessions[i]._calls[j].GenParam != nil {
								ss._sessions[i]._calls[j].Method, ss._sessions[i]._calls[j].Type, ss._sessions[i]._calls[j].URL, ss._sessions[i]._calls[j].Body = ss._sessions[i]._calls[j].GenParam()
							}
							return ss._sessions[i]._calls[j], nil
						}
					}
				}
			default:
				continue
			}
		}
	}

	log.Fatal("what? should never reach here")
	return nil, errors.New("all sessions are being initialized")
}
开发者ID:chenchaoyi,项目名称:hammer2,代码行数:34,代码来源:session_scenario.go

示例9: PickRule

func (self *LSystem) PickRule(name string, random *rand.Rand) int {

	// Sum up the weights of all rules with this name:
	var sum int = 0
	for _, rule := range self.Rules {
		if rule.Name != name {
			continue
		}
		weight := rule.Weight
		sum += weight
	}

	// Choose a rule at random:
	n := random.Intn(sum)
	for i, rule := range self.Rules {
		if rule.Name != name {
			continue
		}
		weight := rule.Weight
		if n < weight {
			return i
		}
		n -= weight
	}

	fmt.Println("Error.")
	return -1
}
开发者ID:prideout,项目名称:lsystem,代码行数:28,代码来源:lsystem.go

示例10: Apply

// Apply partially mixed crossover.
func (c CrossPMX) Apply(p1 Individual, p2 Individual, rng *rand.Rand) (Individual, Individual) {
	var (
		nbGenes = len(p1.Genome)
		o1      = makeIndividual(nbGenes, rng)
		o2      = makeIndividual(nbGenes, rng)
	)
	copy(o1.Genome, p1.Genome)
	copy(o2.Genome, p2.Genome)
	// Choose a random crossover point p such that 0 < p < (nbGenes - 1)
	var (
		p = rng.Intn(nbGenes-2) + 1
		a int
		b int
	)
	// Paste the father's genome up to the crossover point
	for i := 0; i < p; i++ {
		// Find where the second parent's gene is in the first offspring's genome
		a = getIndex(p2.Genome[i], o1.Genome)
		// Swap the genes
		o1.Genome[a], o1.Genome[i] = o1.Genome[i], p2.Genome[i]
		// Find where the first parent's gene is in the second offspring's genome
		b = getIndex(p1.Genome[i], o2.Genome)
		// Swap the genes
		o2.Genome[b], o2.Genome[i] = o2.Genome[i], p1.Genome[i]
	}
	return o1, o2
}
开发者ID:MaxHalford,项目名称:gago,代码行数:28,代码来源:crossover.go

示例11: randCoord

func randCoord(r *rand.Rand) []int {
	var coord []int = make([]int, 3)
	coord[0] = r.Intn(S_MAP)
	coord[1] = r.Intn(S_MAP)
	coord[2] = r.Intn(S_MAP)
	return coord
}
开发者ID:jinseokYeom,项目名称:GoDWIB,代码行数:7,代码来源:GoDWIB.go

示例12: replaceLabels

func replaceLabels(l *lexer, r *rand.Rand) string {
	var buf bytes.Buffer
	var labelCounter uint
	var remLabels []uint

	for i := l.nextItem(); i.typ != itemEOF; i = l.nextItem() {
		switch i.typ {
		case itemText:
			buf.WriteString(i.val)
		case itemLabel:
			buf.WriteString("label")
			buf.WriteString(strconv.Itoa(int(labelCounter)))
			remLabels = append(remLabels, labelCounter)
			labelCounter++
		case itemNewLine:
			buf.WriteString("\n")

			// randomly put a label here, if any
			if len(remLabels) > 0 && r.Intn(8) == 0 {
				buf.WriteString("label")
				buf.WriteString(strconv.Itoa(int(remLabels[0])))
				buf.WriteString(":\n")
				remLabels = remLabels[1:]
			}
		}
	}

	for _, l := range remLabels {
		buf.WriteString("label")
		buf.WriteString(strconv.Itoa(int(l)))
		buf.WriteString(":\n")
	}

	return buf.String()
}
开发者ID:yblein,项目名称:tavor-isa,代码行数:35,代码来源:post.go

示例13: randomColor

// randomColor returns a random RGB color from a random seed.
func randomColor(seed *rand.Rand) color.RGBA {
	return color.RGBA{
		uint8(seed.Intn(255)),
		uint8(seed.Intn(255)),
		uint8(seed.Intn(255)),
		0xff} // No alpha.
}
开发者ID:karlek,项目名称:vanilj,代码行数:8,代码来源:fractal.go

示例14: ensureExits

// ensureExits makes sure there is an outside exit on two sides
// of the room. The corners are left alone.
func (rms *rooms) ensureExits(random *rand.Rand, rm *room) {
	var top, bot, left, right []*cell
	xmax, ymax := rm.w, rm.h
	for x := rm.x + 1; x < rm.x+rm.w-1; x++ {
		u := rms.cells[x][rm.y]
		if u.isWall {
			top = append(top, u)
		}
		u = rms.cells[x][rm.y+rm.h-1]
		if u.isWall {
			bot = append(bot, u)
		}
	}
	for y := rm.y + 1; y < rm.y+rm.h-1; y++ {
		u := rms.cells[rm.x][y]
		if u.isWall {
			left = append(left, u)
		}
		u = rms.cells[rm.x+rm.w-1][y]
		if u.isWall {
			right = append(right, u)
		}
	}

	// randomize which sides get exits.
	if random.Intn(2) == 0 {
		rms.ensureExit(random, top, xmax-2)
		rms.ensureExit(random, left, ymax-2)
	} else {
		rms.ensureExit(random, bot, xmax-2)
		rms.ensureExit(random, right, ymax-2)
	}
}
开发者ID:krattai,项目名称:monoflow,代码行数:35,代码来源:rooms.go

示例15: run

func (s *sim) run(t *testing.T, rng *rand.Rand) {
	dbg(s.graph.Graph().Map())

	step := 0
	for len(s.pending) > 0 {
		if step > 1000000 {
			t.Fatal("non-convergence")
		}
		step++

		// Maybe add or remove a link
		if rng.Intn(100) == 0 {
			e := s.graph.RandomEdge(rng)
			if s.graph.Contains(e) {
				s.graph.Remove(e)

				// Check that the graph did not become
				// disconnected.
				if s.graph.Graph().Connected() {
					dbg("Disconnecting", e)
					s.disconnect(e)
				} else {
					s.graph.Add(e)
				}
			} else {
				dbg("Connecting", e)
				s.graph.Add(e)
				s.link(e)
			}
		}

		// Propagate an update
		i := rng.Intn(len(s.pending))
		l := s.pending[i]
		s.pending[i] = s.pending[len(s.pending)-1]
		s.pending = s.pending[:len(s.pending)-1]

		if l.closed {
			continue
		}

		for prop, updates := range l.sender.Outgoing() {
			dbg(l.sender.c.id, "->", l.receiver.c.id, ":", updates)
			l.receiver.Incoming(l.receiver.c.ConnectivityPropagation(), updates)
			l.sender.Delivered(prop, updates)
		}
	}

	var expect map[NodeID]interface{}
	var expectNode NodeID
	for _, node := range s.graph.Nodes {
		c := s.cs[node]
		if expect == nil {
			expect = c.Dump()
			expectNode = node
		} else {
			require.Equal(t, expect, c.Dump(), "mismatch %s %s", expectNode, node)
		}
	}
}
开发者ID:squaremo,项目名称:monotreme,代码行数:60,代码来源:connectivity_test.go


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