Example #1
0
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)
	}
}
Example #2
0
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)
}
Example #3
0
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
}
Example #4
0
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
}
Example #5
0
// 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)
}
Example #6
0
// 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]
	}
}
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
}
Example #8
0
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")
}
Example #9
0
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
}
Example #10
0
// 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
}
Example #11
0
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
}
Example #12
0
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()
}
Example #13
0
// 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.
}
Example #14
0
// 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)
	}
}
Example #15
0
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)
		}
	}
}
Example #16
0
// RandColumnType returns a random ColumnType_Kind value.
func RandColumnType(rng *rand.Rand) ColumnType {
	typ := ColumnType{Kind: columnKinds[rng.Intn(len(columnKinds))]}
	if typ.Kind == ColumnType_COLLATEDSTRING {
		typ.Locale = &collationLocales[rng.Intn(len(collationLocales))]
	}
	return typ
}
Example #17
0
func (RemoveSliceTestInput) Generate(rand *rand.Rand, size int) reflect.Value {
	ret := RemoveSliceTestInput{}

	// Keep searching for a non-zero length input.  Technically this could run forever, but
	// realistically it won't.  Thus I don't care too much.
	for len(ret.Input) == 0 {
		val, ok := quick.Value(reflect.TypeOf(testIntSlice{}), rand)
		if ok != true {
			panic("Failed to generate input slice elements!!!!!")
		}
		ret.Input = val.Interface().(testIntSlice)
	}

	removeElementSize := rand.Intn(len(ret.Input))
	ret.ToRemove = make(testIntSlice, removeElementSize)

	for index := range ret.ToRemove {
		ret.ToRemove[index] = ret.Input[rand.Intn(len(ret.Input))]
	}

	// Random numbers may generate dups.  Just remove them brute force style.
	ret.Input.RemoveDuplicates()
	ret.ToRemove.RemoveDuplicates()
	sort.Sort(ret.Input)
	sort.Sort(ret.ToRemove)

	return reflect.ValueOf(ret)
}
Example #18
0
// replaceWithGenerated replaces all occurrences of the given expression
// in the string with random characters of the specified range and length.
func replaceWithGenerated(s *string, expression string, ranges [][]byte, length int, seed *rand.Rand) error {
	var alphabet string
	for _, r := range ranges {
		switch string(r[0]) + string(r[1]) {
		case `\w`:
			alphabet += ASCII
		case `\d`:
			alphabet += Numerals
		case `\a`:
			alphabet += Alphabet + Numerals
		default:
			slice, err := alphabetSlice(r[0], r[1])
			if err != nil {
				return err
			}
			alphabet += slice
		}
	}
	result := make([]byte, length)
	for i := 0; i < length; i++ {
		result[i] = alphabet[seed.Intn(len(alphabet))]
	}
	*s = strings.Replace(*s, expression, string(result), 1)
	return nil
}
Example #19
0
func randomCircle(r *rand.Rand) {
	colors := [12]string{
		"#ff66cc",
		"#ff6680",
		"#ff9966",
		"#ffe666",
		"#ccff66",
		"#80ff66",
		"#66ff99",
		"#66ffe6",
		"#66ccff",
		"#6680ff",
		"#9966ff",
		"#e566ff",
	}
	x := int(r.Float64()*width + 1)
	y := int(r.Float64()*height + 1)
	radius := int((r.Float64() * width / 5) + 1)
	strokeColor := colors[r.Intn(len(colors))]
	strokeWidth := 4
	color := colors[r.Intn(len(colors))]

	fmt.Printf("<circle cx='%d' cy='%d' r='%d' stroke='%s' "+
		"stroke-width='%d' fill='%s' />\n", x, y, radius,
		strokeColor, strokeWidth, color)
}
Example #20
0
// Picks a random index from a, with a probability proportional to its value.
// Using a local random-generator to prevent waiting on rand's default source.
func pickRandom(a []float64, rnd *rand.Rand) int {
	if len(a) == 0 {
		panic("Cannot pick element from an empty distribution.")
	}

	sum := float64(0)
	for i := range a {
		if a[i] < 0 {
			panic(fmt.Sprintf("Got negative value in distribution: %v", a[i]))
		}
		sum += a[i]
	}
	if sum == 0 {
		return rnd.Intn(len(a))
	}

	r := rnd.Float64() * sum
	i := 0
	for i < len(a) && r > a[i] {
		r -= a[i]
		i++
	}
	if i == len(a) {
		i--
	}
	return i
}
Example #21
0
func GenerateHeroOccupation(r *rand.Rand, race Race, occupation Occupation) *Hero {
	hero := &Hero{}
	world.InitObject(hero)
	hero.mtx.Lock()
	defer hero.mtx.Unlock()
	hero.birth = time.Now().UTC()
	hero.race = race
	hero.occupation = occupation
	hero.gender = race.Genders()[r.Intn(len(race.Genders()))]
	hero.skinTone = uint(r.Intn(len(race.SkinTones())))
	switch race {
	case RaceHuman:
		hero.name = GenerateHumanName(r, hero.gender)
	}
	hero.equip(&Equip{
		slot:         SlotShirt,
		kind:         0,
		customColors: []string{randomColor(r)},
	})
	hero.equip(&Equip{
		slot:         SlotPants,
		kind:         0,
		customColors: []string{randomColor(r)},
	})
	hero.equip(&Equip{
		slot: SlotFeet,
		kind: 0,
	})
	return hero
}
Example #22
0
func randomString(r *rand.Rand, n int) []byte {
	b := new(bytes.Buffer)
	for i := 0; i < n; i++ {
		b.WriteByte(' ' + byte(r.Intn(95)))
	}
	return b.Bytes()
}
Example #23
0
func genRandBytes(rnd *rand.Rand, n int) []byte {
	res := make([]byte, n, n)
	for i := 0; i < n; i++ {
		res[i] = byte(rnd.Intn(256))
	}
	return res
}
Example #24
0
// Ian: Different from Lucene's default random class initializer, I have to
// explicitly initialize different directory randomly.
func newDirectoryImpl(random *rand.Rand, clazzName string) store.Directory {
	if clazzName == "random" {
		if Rarely(random) {
			switch random.Intn(1) {
			case 0:
				clazzName = "SimpleFSDirectory"
			}
		} else {
			clazzName = "RAMDirectory"
		}
	}
	if clazzName == "RAMDirectory" {
		return store.NewRAMDirectory()
	} else {
		path := TempDir("index")
		if err := os.MkdirAll(path, os.ModeTemporary); err != nil {
			panic(err)
		}
		switch clazzName {
		case "SimpleFSDirectory":
			d, err := store.NewSimpleFSDirectory(path)
			if err != nil {
				panic(err)
			}
			return d
		}
		panic(fmt.Sprintf("not supported yet: %v", clazzName))
	}
}
Example #25
0
func GenerateDense(r *rand.Rand, size int) Undirected {
	for {
		u := Undirected{
			Nodes: make([]NodeID, size),
			Edges: make(map[Edge]struct{}),
		}

		for i := 0; i < size; i++ {
			u.Nodes[i] = NodeID(strconv.Itoa(i))
		}

		// Form a fully-connected graph
		for i := 0; i < size; i++ {
			for j := 0; j < i; j++ {
				u.Add(Edge{u.Nodes[i], u.Nodes[j]})
			}
		}

		// Remove some edges
		for i := r.Intn(size); i > 0; i-- {
			u.Remove(u.RandomEdge(r))
		}

		if u.Graph().Connected() {
			return u
		}
	}
}
Example #26
0
func NewField(r *rand.Rand, name, value string, typ *index.FieldType) *index.Field {
	if Usually(r) || !typ.Indexed() {
		// most of the time, don't modify the params
		return index.NewStringField(name, value, typ)
	}

	newType := index.NewFieldTypeFrom(typ)
	if !newType.Stored() && r.Intn(2) == 0 {
		newType.SetStored(true) // randonly store it
	}

	if !newType.StoreTermVectors() && r.Intn(2) == 0 {
		newType.SetStoreTermVectors(true)
		if !newType.StoreTermVectorOffsets() {
			newType.SetStoreTermVectorOffsets(r.Intn(2) == 0)
		}
		if !newType.StoreTermVectorPositions() {
			newType.SetStoreTermVectorPositions(r.Intn(2) == 0)

			if newType.StoreTermVectorPositions() && !newType.StoreTermVectorPayloads() && !PREFLEX_IMPERSONATION_IS_ACTIVE {
				newType.SetStoreTermVectorPayloads(r.Intn(2) == 2)
			}
		}
	}

	return index.NewStringField(name, value, newType)
}
Example #27
0
func fillPix(r *rand.Rand, pixs ...[]byte) {
	for _, pix := range pixs {
		for i := range pix {
			pix[i] = uint8(r.Intn(256))
		}
	}
}
Example #28
0
// rndMessages generates several random Protocol Buffer messages.
func rndMessages(r *rand.Rand) []Message {
	n := r.Intn(128)
	out := make([]Message, 0, n)
	for i := 0; i < n; i++ {
		out = append(out, rndMessage(r))
	}
	return out
}
Example #29
0
func randByteSlice(rand *rand.Rand, minSize, maxSize int) []byte {
	n := rand.Intn(maxSize-minSize) + minSize
	b := make([]byte, n)
	for i := 0; i < n; i++ {
		b[i] = byte(rand.Intn(255))
	}
	return b
}
Example #30
0
// randString makes a random string up to 20 characters long. The returned string
// may include a variety of (valid) UTF-8 encodings.
func randString(r *rand.Rand) string {
	n := r.Intn(20)
	runes := make([]rune, n)
	for i := range runes {
		runes[i] = unicodeRanges[r.Intn(len(unicodeRanges))].choose(r)
	}
	return string(runes)
}