Пример #1
0
func merge(string1 string, string2 string) string {

	if len(string1) == 0 {
		return string2

	}

	if len(string2) == 0 {
		return string1
	}

	if len(string1) == 1 && len(string2) == 1 {
		if rand.Float32() < .5 {
			return string1 + string2
		}
		return string2 + string1
	}

	for i := 0; i < len(string1); i++ {
		for j := 0; j < len(string2); j++ {
			if string1[i] == string2[j] && rand.Float32() < mergesame {

				return merge(string1[:i], string2[:j]) + string(string1[i]) + merge(string1[i+1:], string2[j+1:])

			}
		}
	}

	a := rand.Int() % len(string1)
	b := rand.Int() % len(string2)
	return merge(string1[:a], string2[:b]) + merge(string1[a:], string2[b:])

}
Пример #2
0
Файл: pos.go Проект: samuell/exp
func RandLen(x float32) XYZ {
	return XYZ{
		X: rand.Float32() - 1/2,
		Y: rand.Float32() - 1/2,
		Z: rand.Float32() - 1/2,
	}.Norm().Mul(x)
}
Пример #3
0
func (sp *EnemeyAI) OnDie(byTimer bool) {

	sxps := 4
	size := float32(0.5)
	if sp.Type == Enemey_Boss {
		sxps = 10
		size = 3
		Wall.Destroy()
		queenDead = true
	} else {
		CreatePowerUp(sp.Transform().WorldPosition())
	}

	for i := 0; i < sxps; i++ {
		n := Explosion.Clone()
		n.Transform().SetParent2(GameSceneGeneral.Layer1)
		n.Transform().SetWorldPosition(sp.Transform().WorldPosition())
		s := n.Transform().Scale()
		n.Transform().SetScale(s.Mul2((rand.Float32() * 3) + size))
		n.AddComponent(engine.NewPhysics(false))

		n.Transform().SetRotationf(rand.Float32() * 360)
		rot := n.Transform().Direction()
		n.Physics.Body.SetVelocity(-rot.X*15, -rot.Y*15)

		n.Physics.Body.SetMass(1)
		n.Physics.Shape.Group = 1
		n.Physics.Shape.IsSensor = true
	}

	sp.GameObject().Destroy()
}
Пример #4
0
Файл: pos.go Проект: samuell/exp
func Rand(s float32) XYZ {
	return XYZ{
		X: rand.Float32()*s - s/2,
		Y: rand.Float32()*s - s/2,
		Z: rand.Float32()*s - s/2,
	}
}
Пример #5
0
func TestMinPHeap(t *testing.T) {
	Convey("Test that output after random input is sorted.", t, func() {
		m := New()
		for i := 0; i < 1000; i++ {
			m.Insert(i, rand.Float32())
		}
		_, prev := m.Pop()
		for i := 0; i < 999; i++ {
			_, key := m.Pop()
			So(key, ShouldBeGreaterThanOrEqualTo, prev)
			prev = key
		}
	})

	Convey("Test DecreaseKey.", t, func() {
		m := New()
		for i := 0; i < 1000; i++ {
			m.Insert(i, rand.Float32())
		}
		for i := 0; i < 1000; i++ {
			val, _ := m.PeekAtVal(i)
			m.DecreaseKey(i, val-1)
		}
		_, prev := m.Pop()
		for i := 0; i < 999; i++ {
			_, key := m.Pop()
			So(key, ShouldBeGreaterThanOrEqualTo, prev)
			prev = key
		}
	})
}
Пример #6
0
func init() {
	rand.Seed(4)

	// create random samples
	fmt.Printf("generating %d random %d-D test samples...\n", N, D)
	samples := make([]point, N)
	for i := range samples {
		samples[i] = make([]float32, D)
		for d := 0; d < D; d++ {
			samples[i][d] = rand.Float32()
		}
	}
	// make interfaced samples
	isamples = make([]Point, len(samples))
	for i := range isamples {
		isamples[i] = &samples[i]
	}

	// create random queries
	fmt.Printf("generating %d random %d-D test queries...\n", N, D)
	queries := make([]point, N)
	for i := range queries {
		queries[i] = make([]float32, D)
		for d := 0; d < D; d++ {
			queries[i][d] = rand.Float32()
		}
	}
	// make interfaced queries
	iqueries = make([]Point, len(queries))
	for i := range iqueries {
		iqueries[i] = &queries[i]
	}
}
Пример #7
0
// createPhoto looks up or creates a new user to match userID (it's
// the only method in this interface which doesn't match an existing
// user except for createUser). It then creates a new photo for the
// new or pre-existing user.
func createPhoto(tx *sql.Tx, userID int) error {
	if err := createUser(tx, userID); err != nil {
		return err
	}

	const insertSQL = `
INSERT INTO photos VALUES (DEFAULT, $1, 0, $2, $3, $4, NOW());
`
	const minCaptionLen = 10
	const maxCaptionLen = 200
	caption := randString(minCaptionLen + rand.Intn(maxCaptionLen-minCaptionLen))
	latitude := rand.Float32() * 90
	longitude := rand.Float32() * 180
	if _, err := tx.Exec(insertSQL, userID, caption, latitude, longitude); err != nil {
		return err
	}

	const updateSQL = `
UPDATE users SET photoCount = photoCount + 1 WHERE id = $1;
`
	if _, err := tx.Exec(updateSQL, userID); err != nil {
		return err
	}
	return nil
}
Пример #8
0
func (packer *GrainPacker) Generate() []*api.Grain {
	const groundOffset = 0.1
	const noiseAmplitude = 0.001

	offset := packer.org.Add(Vec3f{0, 0, groundOffset})

	var grains []*api.Grain
	for iz := 0; iz < packer.nz; iz++ {
		for ix := 0; ix < packer.nx; ix++ {
			for iy := 0; iy < packer.ny; iy++ {
				for _, unitOffset := range packer.generateUnitOffsets() {
					baseIndex := Vec3f{float32(ix), float32(iy), float32(iz)}
					pos := baseIndex.Add(unitOffset).MultS(packer.latticeSize).Add(offset)
					if packer.natural {
						noiseBase := Vec3f{rand.Float32(), rand.Float32(), rand.Float32()}.MultS(2).SubS(1)
						pos = pos.Add(noiseBase.MultS(noiseAmplitude))
					}
					grains = append(grains, &api.Grain{
						Id:       uint64(ix + 1),
						Pos:      &api.CkPosition{pos.X, pos.Y, pos.Z},
						Vel:      &api.CkVelocity{0, 0, 0},
						Kind:     packer.grainType,
						CellProp: packer.MaybeGenerateCellProp(),
					})
				}

			}
		}
	}
	return grains
}
Пример #9
0
func randomTracks(num int) []*Track {
	tracks := make([]*Track, num)

	for i := 0; i < num; i++ {
		var year int = rand.Int()%115 + 1900
		var month int = rand.Int()%12 + 1
		var day int = rand.Int()%29 + 1

		var str_date = fmt.Sprintf("%d-%02d-%02d", year, month, day)

		var date = parseTime(str_date)

		tracks[i] = &Track{
			date:   date,
			symbol: RandString(4),
			open:   rand.Float32(),
			high:   rand.Float32(),
			low:    rand.Float32(),
			end:    rand.Float32(),
		}
	}

	sort.Sort(TrackByDate(tracks))

	return tracks
}
Пример #10
0
func (bs *BallSystem) Update(entity *ecs.Entity, dt float32) {
	var space *engi.SpaceComponent
	var speed *SpeedComponent
	if !entity.Component(&space) || !entity.Component(&speed) {
		return
	}

	if space.Position.X < 0 {
		engi.Mailbox.Dispatch(ScoreMessage{1})

		space.Position.X = 400 - 16
		space.Position.Y = 400 - 16
		speed.X = 800 * rand.Float32()
		speed.Y = 800 * rand.Float32()
	}

	if space.Position.Y < 0 {
		space.Position.Y = 0
		speed.Y *= -1
	}

	if space.Position.X > (800 - 16) {
		engi.Mailbox.Dispatch(ScoreMessage{2})

		space.Position.X = 400 - 16
		space.Position.Y = 400 - 16
		speed.X = 800 * rand.Float32()
		speed.Y = 800 * rand.Float32()
	}

	if space.Position.Y > (800 - 16) {
		space.Position.Y = 800 - 16
		speed.Y *= -1
	}
}
Пример #11
0
func TestReadComplex64(t *testing.T) {
	var buf bytes.Buffer
	wr := NewWriter(&buf)
	rd := NewReader(&buf)

	for i := 0; i < 100; i++ {
		buf.Reset()
		f := complex(rand.Float32()*math.MaxFloat32, rand.Float32()*math.MaxFloat32)

		wr.WriteComplex64(f)
		err := wr.Flush()
		if err != nil {
			t.Fatal(err)
		}

		out, err := rd.ReadComplex64()
		if err != nil {
			t.Error(err)
			continue
		}

		if out != f {
			t.Errorf("Wrote %f; read %f", f, out)
		}

	}
}
Пример #12
0
func main() {
	data := [][]v3{}
	world := world_new()
	vdu := v3_divs(v3_sub(world.camera.rt, world.camera.lt), Width)
	vdv := v3_divs(v3_sub(world.camera.lb, world.camera.lt), Height)

	data = make([][]v3, Height)

	for y := 0; y < Height; y++ {
		data[y] = make([]v3, Width)

		for x := 0; x < Width; x++ {
			color := zero
			ray := ray{}

			ray.origin = world.camera.eye

			for i := 0; i < Samples; i++ {
				ray.direction = v3_unit(
					v3_sub(
						v3_add(
							world.camera.lt,
							v3_add(v3_muls(vdu, float32(x)+rand.Float32()),
								v3_muls(vdv, float32(y)+rand.Float32()))),
						world.camera.eye))
				color = v3_add(color, trace(world, ray, 0))
			}

			color = v3_divs(color, Samples)
			data[y][x] = color
		}
	}

	writeppm(data)
}
Пример #13
0
func (ms *Missle) OnDie(byTimer bool) {
	if ms.Explosion == nil {
		ms.GameObject().Destroy()
		return
	}
	if ms.GameObject() == nil {
		return
	}
	if !byTimer {
		for i := 0; i < 2; i++ {
			n := ms.Explosion.Clone()
			n.Transform().SetParent2(GameSceneGeneral.Layer1)
			n.Transform().SetWorldPosition(ms.Transform().WorldPosition())
			s := n.Transform().Scale()
			n.Transform().SetScale(s.Mul2(rand.Float32() + 0.5))
			n.AddComponent(engine.NewPhysics(false))
			n.Transform().SetRotationf(rand.Float32() * 360)
			rot := n.Transform().Direction()
			n.Physics.Body.SetVelocity(-rot.X*10, -rot.Y*10)

			n.Physics.Body.SetMass(1)
			n.Physics.Shape.Group = 1
			n.Physics.Shape.IsSensor = true
		}
	}
	ms.GameObject().Destroy()
}
Пример #14
0
func (suite *AnnoyTestSuite) TestLargeEuclideanIndex() {
	index := annoyindex.NewAnnoyIndexEuclidean(10)

	for j := 0; j < 10000; j += 2 {
		p := make([]float32, 0, 10)
		for i := 0; i < 10; i++ {
			p = append(p, rand.Float32())
		}
		x := make([]float32, 0, 10)
		for i := 0; i < 10; i++ {
			x = append(x, 1+p[i]+rand.Float32()*1e-2)
		}
		y := make([]float32, 0, 10)
		for i := 0; i < 10; i++ {
			y = append(y, 1+p[i]+rand.Float32()*1e-2)
		}
		index.AddItem(j, x)
		index.AddItem(j+1, y)
	}
	index.Build(10)
	for j := 0; j < 10000; j += 2 {
		var result []int
		index.GetNnsByItem(j, 2, -1, &result)

		assert.Equal(suite.T(), result, []int{j, j + 1})

		index.GetNnsByItem(j+1, 2, -1, &result)
		assert.Equal(suite.T(), result, []int{j + 1, j})
	}
	annoyindex.DeleteAnnoyIndexEuclidean(index)
}
Пример #15
0
func (b *BounceSystem) Update(dt float32) {
	for _, e := range b.entities {
		if e.SpaceComponent.Position.X < 0 {
			engo.Mailbox.Dispatch(ScoreMessage{1})

			e.SpaceComponent.Position.X = 400 - 16
			e.SpaceComponent.Position.Y = 400 - 16
			e.SpeedComponent.X = 800 * rand.Float32()
			e.SpeedComponent.Y = 800 * rand.Float32()
		}

		if e.SpaceComponent.Position.Y < 0 {
			e.SpaceComponent.Position.Y = 0
			e.SpeedComponent.Y *= -1
		}

		if e.SpaceComponent.Position.X > (800 - 16) {
			engo.Mailbox.Dispatch(ScoreMessage{2})

			e.SpaceComponent.Position.X = 400 - 16
			e.SpaceComponent.Position.Y = 400 - 16
			e.SpeedComponent.X = 800 * rand.Float32()
			e.SpeedComponent.Y = 800 * rand.Float32()
		}

		if e.SpaceComponent.Position.Y > (800 - 16) {
			e.SpaceComponent.Position.Y = 800 - 16
			e.SpeedComponent.Y *= -1
		}
	}
}
Пример #16
0
func main() {
	tree := llrb.New(CompareByX)
	points := []Pt{}
	numPoints := 100000
	for i := 0; i < numPoints; i++ {
		points = append(points, Pt{rand.Float32(), rand.Float32()})
	}
	startInsert := time.Now()
	for _, dasPt := range points {
		tree.ReplaceOrInsert(dasPt)
		//fmt.Printf("Inserted point %v\n", dasPt)
		//llrb.PrintTree(tree.Root(), 0)
		//fmt.Println("")
	}
	elapsedInsert := time.Since(startInsert)

	pointIndexes := make([]int, numPoints)
	for i := 0; i < numPoints; i++ {
		pointIndexes[i] = i
	}
	rand.Seed(time.Now().UnixNano())
	Shuffle(pointIndexes)
	startDelete := time.Now()
	for i, v := range pointIndexes {
		fmt.Printf("Iteration %d/%d: deleting index %d %v\n", i, numPoints, v, points[v])
		tree.Delete(points[v])
	}
	elapsedDelete := time.Since(startDelete)
	fmt.Printf("INS %d points in %v\n", len(points), elapsedInsert)
	fmt.Printf("DEL %d points in %v\n", len(points), elapsedDelete)
}
Пример #17
0
func init() {
	rand.Seed(0)
	demodBenchSamples = make([]complex64, benchSize)
	for i := 0; i < benchSize; i++ {
		demodBenchSamples[i] = complex(rand.Float32(), rand.Float32())
	}
}
Пример #18
0
func TestPopulate(t *testing.T) {

	sess, err := db.Open("mongo", db.DataSource{Host: host, Database: dbname})

	if err != nil {
		t.Errorf(err.Error())
		return
	}

	defer sess.Close()

	people, _ := sess.Collection("people")
	places, _ := sess.Collection("places")
	children, _ := sess.Collection("children")
	visits, _ := sess.Collection("visits")

	values := []string{"Alaska", "Nebraska", "Alaska", "Acapulco", "Rome", "Singapore", "Alabama", "Cancún"}

	for i, value := range values {
		places.Append(db.Item{
			"code_id": i,
			"name":    value,
		})
	}

	results := people.FindAll(
		db.Fields{"id", "name"},
		db.Sort{"name": "ASC", "id": -1},
	)

	for _, person := range results {

		// Has 5 children.

		for j := 0; j < 5; j++ {
			children.Append(db.Item{
				"name":      fmt.Sprintf("%s's child %d", person["name"], j+1),
				"parent_id": person["_id"],
			})
		}

		// Lives in
		people.Update(
			db.Cond{"_id": person["_id"]},
			db.Set{"place_code_id": int(rand.Float32() * float32(len(results)))},
		)

		// Has visited
		for k := 0; k < 3; k++ {
			place := places.Find(db.Cond{
				"code_id": int(rand.Float32() * float32(len(results))),
			})
			visits.Append(db.Item{
				"place_id":  place["_id"],
				"person_id": person["_id"],
			})
		}
	}

}
Пример #19
0
func populate(grid []rune, w, h int, letter_freqs []pair_lf, word string, pos int) ([]rune, bool) {
	valid := false
	var newgrid []rune
	if pos == -1 {
		grid_size := w * h
		positions := make([]int, grid_size)
		for i := 0; i < grid_size; i++ {
			positions[i] = i
		}
		for !valid && len(positions) > 0 {
			r := int(rand.Float32() * float32(len(positions)))
			position := positions[r]
			positions_new := append(positions[:r], positions[r+1:]...)
			positions = positions_new
			newgrid, valid = populate(grid, w, h, letter_freqs, word, position)
		}
		return newgrid, valid
	}
	if grid[pos] != 0 {
		return nil, false
	}
	newgrid = make([]rune, len(grid))
	copy(newgrid, grid)
	newrune, runesize := utf8.DecodeRuneInString(word)
	newgrid[pos] = newrune
	if utf8.RuneCountInString(word) == 1 {
		valid = true
		for y := 0; y < h; y++ {
			for x := 0; x < w; x++ {
				idx := y*w + x
				if newgrid[idx] == 0 {
					sample := rand.Float32()
					newgrid[idx] = sample_letter(letter_freqs, sample)
				}
			}
		}
		return newgrid, valid
	}
	newword := word[runesize:]
	positions := make([]int, 0)
	for m := N; m < NW; m++ {
		idx := move(pos, w, h, m)
		if idx == -1 {
			continue
		}
		positions = append(positions, idx)
	}
	for len(positions) > 0 && !valid {
		var resultgrid []rune
		r := int(rand.Float32() * float32(len(positions)))
		position := positions[r]
		positions = append(positions[:r], positions[r+1:]...)
		resultgrid, valid = populate(newgrid, w, h, letter_freqs, newword, position)
		if valid {
			newgrid = resultgrid
		}
	}
	return newgrid, valid
}
Пример #20
0
func (p Arr) FillRandom(Lmax, Wmax float32) {
	for i := range p {
		for idim := range p[i].Pos {
			p[i].Pos[idim] = rand.Float32() * Lmax
		}
		p[i].W = rand.Float32() * Wmax
	}
}
Пример #21
0
func (c *Critter) initAlienVelocity() {
	// Choose random velocity
	// This peculiar 2D distibution was in the original sources.
	// It was probably an error, but is now traditional in Frequon Invaders.
	// It biases towards diagonal directions
	c.vx = math32.Cos(2*π*rand.Float32()) * velocityMax
	c.vy = math32.Sin(2*π*rand.Float32()) * velocityMax
}
Пример #22
0
func init() {
	vf = make([]float32, 514)
	wf = make([]float32, len(vf))
	for i := 0; i < len(vf); i++ {
		vf[i] = rand.Float32()
		wf[i] = rand.Float32()
	}
}
Пример #23
0
func TestSqPopulate(t *testing.T) {
	var i int

	sess := SqliteSession(db.DataSource{Database: sqDatabase})

	err := sess.Open()
	defer sess.Close()

	if err != nil {
		panic(err)
	}

	sess.Use("test")

	places := []string{"Alaska", "Nebraska", "Alaska", "Acapulco", "Rome", "Singapore", "Alabama", "Cancún"}

	for i = 0; i < len(places); i++ {
		sess.Collection("places").Append(db.Item{
			"code_id": i,
			"name":    places[i],
		})
	}

	people := sess.Collection("people").FindAll(
		db.Fields{"id", "name"},
		db.Sort{"name": "ASC", "id": -1},
	)

	for i = 0; i < len(people); i++ {
		person := people[i]

		// Has 5 children.
		for j := 0; j < 5; j++ {
			sess.Collection("children").Append(db.Item{
				"name":      fmt.Sprintf("%s's child %d", person["name"], j+1),
				"parent_id": person["id"],
			})
		}

		// Lives in
		sess.Collection("people").Update(
			db.Cond{"id": person["id"]},
			db.Set{"place_code_id": int(rand.Float32() * float32(len(places)))},
		)

		// Has visited
		for k := 0; k < 3; k++ {
			place := sess.Collection("places").Find(db.Cond{
				"code_id": int(rand.Float32() * float32(len(places))),
			})
			sess.Collection("visits").Append(db.Item{
				"place_id":  place["id"],
				"person_id": person["id"],
			})
		}
	}

}
Пример #24
0
func (grouter *TestRouter) run(sender mesh.PeerName, gossiper mesh.Gossiper, gossipChan chan interface{}) {
	gossipTimer := time.Tick(2 * time.Second)
	for {
		select {
		case gossip := <-gossipChan:
			switch message := gossip.(type) {
			case exitMessage:
				close(message.exitChan)
				return

			case flushMessage:
				close(message.flushChan)

			case unicastMessage:
				if rand.Float32() > (1.0 - grouter.loss) {
					continue
				}
				if err := gossiper.OnGossipUnicast(message.sender, message.buf); err != nil {
					panic(fmt.Sprintf("Error doing gossip unicast to %s: %s", message.sender, err))
				}

			case broadcastMessage:
				if rand.Float32() > (1.0 - grouter.loss) {
					continue
				}
				for _, msg := range message.data.Encode() {
					if _, err := gossiper.OnGossipBroadcast(message.sender, msg); err != nil {
						panic(fmt.Sprintf("Error doing gossip broadcast: %s", err))
					}
				}
			case gossipMessage:
				if rand.Float32() > (1.0 - grouter.loss) {
					continue
				}
				for _, msg := range message.data.Encode() {
					diff, err := gossiper.OnGossip(msg)
					if err != nil {
						panic(fmt.Sprintf("Error doing gossip: %s", err))
					}
					if diff == nil {
						continue
					}
					// Sanity check - reconsuming the diff should yield nil
					for _, diffMsg := range diff.Encode() {
						if nextDiff, err := gossiper.OnGossip(diffMsg); err != nil {
							panic(fmt.Sprintf("Error doing gossip: %s", err))
						} else if nextDiff != nil {
							panic(fmt.Sprintf("Breach of gossip interface: %v != nil", nextDiff))
						}
					}
					grouter.gossip(message.sender, diff)
				}
			}
		case <-gossipTimer:
			grouter.gossip(sender, gossiper.Gossip())
		}
	}
}
Пример #25
0
func GenerateGoods() Goods {

	return Goods{
		{Trade: Trade{Name: "Light Saber", Quantity: rand.Intn(5)}, Price: (rand.Float32() * 20) + 20},
		{Trade: Trade{Name: "Phaser Gun", Quantity: rand.Intn(5)}, Price: (rand.Float32() * 15) + 15},
		{Trade: Trade{Name: "Food Packet", Quantity: rand.Intn(5)}, Price: (rand.Float32() * 5) + 5},
		{Trade: Trade{Name: "Thremal Detonator", Quantity: rand.Intn(5)}, Price: (rand.Float32() * 50) + 50},
	}
}
Пример #26
0
func randomColor() color.RGBA {

	r := uint8(rand.Float32() * 255)
	g := uint8(rand.Float32() * 255)
	b := uint8(rand.Float32() * 255)

	return color.RGBA{r, g, b, 255}

}
Пример #27
0
func (g *Game) nextGroundY() float32 {
	prev := g.groundY[len(g.groundY)-1]
	if change := rand.Intn(groundChangeProb) == 0; change {
		return (groundMax-groundMin)*rand.Float32() + groundMin
	}
	if wobble := rand.Intn(groundWobbleProb) == 0; wobble {
		return prev + (rand.Float32()-0.5)*climbGrace
	}
	return prev
}
Пример #28
0
func (rock *RockSpawnSystem) Update(entity *engi.Entity, dt float32) {
	// 4% change of spawning a rock each frame
	if rand.Float32() < .96 {
		return
	}

	position := engi.Point{0, -32}
	position.X = rand.Float32() * (engi.Width())
	rock.World.AddEntity(NewRock(position))
}
Пример #29
0
func MakeGuest() *Guest {
	return &Guest{
		value:        100.0,
		maxValue:     100.0 + rand.Float32()*100.0,
		boughtOffers: make([]*Offer, 0),
		seenOffers:   make([]*Offer, 0),
		numPlatforms: rand.Intn(4) + 1,
		numOffers:    rand.Intn(5) + 5,
		loyalty:      1.0 + rand.Float32()*0.2,
	}
}
Пример #30
0
func randomVector(space []vector) vector {

	for i, _ := range space {
		space[i].x = (space[i].y - space[i].x) * rand.Float32()
		space[i].y = (space[i].x - space[i].y) * rand.Float32()
	}

	sample := space[rand.Intn(len(space))]

	return sample
}