Golang Perm示例

说明

golang perm示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: math/rand

示例#1
文件: map_string_vs_map_pointer_test.go 项目: xqbumu/learn

func TestMap(t *testing.T) {
	func() {
		d := newMapString()
		ix := rand.Perm(testN)
		for _, v := range testVals {
			d.set(v)
		}
		for _, idx := range ix {
			d.delete(testVals[idx].id)
		}
		for _, idx := range ix {
			if d.exist(testVals[idx].id) {
				t.Errorf("%s should have not existed!", testVals[idx].id)
			}
		}
	}()

	func() {
		d := newMapPointer()
		ix := rand.Perm(testN)
		for _, v := range testVals {
			d.set(v)
		}
		for _, idx := range ix {
			d.delete(testVals[idx].id)
		}
		for _, idx := range ix {
			if d.exist(testVals[idx].id) {
				t.Errorf("%s should have not existed!", testVals[idx].id)
			}
		}
	}()
}

示例#2
文件: rwmutex_vs_mutex_test.go 项目: xqbumu/learn

func TestInterface(t *testing.T) {
	func() {
		d := newDataRWMutex()
		ix := rand.Perm(testSize)
		for _, v := range testValues {
			d.set(v)
		}
		for _, idx := range ix {
			d.delete(testValues[idx])
		}
		for _, idx := range ix {
			if d.exist(testValues[idx]) {
				t.Errorf("%s should have not existed!", testValues[idx])
			}
		}
	}()

	func() {
		d := newDataMutex()
		ix := rand.Perm(testSize)
		for _, v := range testValues {
			d.set(v)
		}
		for _, idx := range ix {
			d.delete(testValues[idx])
		}
		for _, idx := range ix {
			if d.exist(testValues[idx]) {
				t.Errorf("%s should have not existed!", testValues[idx])
			}
		}
	}()
}

示例#3
文件: api.go 项目: offpath/ironpuzzler

func advanceState(c appengine.Context, h *hunt.Hunt, currentState int) {
	err := datastore.RunInTransaction(c, func(c appengine.Context) error {
		h := hunt.ID(c, h.ID)
		if h == nil || h.State != currentState {
			// TODO(dneal): Return a real error.
			return nil
		}
		switch h.State {
		case hunt.StatePreLaunch:
			teams := team.All(c, h)
			nonPaperOrder := rand.Perm(len(teams))
			paperOrder := rand.Perm(len(teams))
			for i := range teams {
				puzzle.New(c, h, teams[i], nonPaperOrder[i]+1, false)
				puzzle.New(c, h, teams[i], len(teams)+paperOrder[i]+1, true)
			}
		case hunt.StateSurveying:
			tally.BuildFinalTally(c, h)
		}
		h.State++
		h.Write(c)
		broadcast.SendRefresh(c, h)
		return nil
	}, nil)
	if err != nil {
		c.Errorf("Error: %v", err)
	}
}

示例#4
文件: perm_test.go 项目: lucmichalski/evo

func TestEdgeX(t *testing.T) {
	mom := rand.Perm(8)
	dad := rand.Perm(8)
	child := make([]int, 8)
	perm.EdgeX(child, mom, dad)
	validate(t, child)
}

示例#5
文件: prev_ag.go 项目: justinkim/avalon

func (ag *AvalonGame) assignSpecialCharacters() {
	// === Good ===
	randomOrder := rand.Perm(ag.NumGoods())
	// Merlin
	ag.SpecialCharacters["merlin"] = ag.GoodCharacters[randomOrder[0]]
	// Percival
	if ag.OptionEnabled[OptionMorganaPercival] {
		ag.SpecialCharacters["percival"] = ag.GoodCharacters[randomOrder[1]]
	}

	// === Evil ===
	randIndex := 1
	randomOrder = rand.Perm(ag.NumEvils())
	// Assassin
	ag.SpecialCharacters["assassin"] = ag.EvilCharacters[randomOrder[0]]
	// Mordred
	if ag.OptionEnabled[OptionMordred] {
		ag.SpecialCharacters["mordred"] = ag.EvilCharacters[randomOrder[randIndex]]
		randIndex++
	}
	// Morgana
	if ag.OptionEnabled[OptionMorganaPercival] {
		ag.SpecialCharacters["morgana"] = ag.EvilCharacters[randomOrder[randIndex]]
		randIndex++
	}
	// Oberon
	if ag.OptionEnabled[OptionOberon] {
		ag.SpecialCharacters["oberon"] = ag.EvilCharacters[randomOrder[randIndex]]
		randIndex++
	}
}

示例#6

func init() {
	for _, val := range rand.Perm(10) {
		data := &TestData{
			Id:    int64(val),
			Value: int64(val),
		}
		skipList.Set(data, nil)
		datas[data.Id] = data
	}

	for _, val := range rand.Perm(20) {
		data := &TestData{
			Id:    int64(val),
			Value: int64(val),
		}
		old, ok := datas[data.Id]
		if ok {
			skipList.Set(data, old)
		} else {
			skipList.Set(data, nil)
		}
	}

	fmt.Println("fuck")
	skipList.Set(&TestData{
		Id:    1,
		Value: 10,
	}, datas[1])
}

示例#7
文件: binarytree_test.go 项目: quarnster/util

func TestBinaryTreeFind(t *testing.T) {
	const count = 100
	for i := 0; i < 10; i++ {
		tree := Tree{Compare: func(a, b interface{}) ComparisonResult {
			aa := a.(int)
			bb := b.(int)
			switch {
			case aa < bb:
				return Less
			case aa > bb:
				return Greater
			default:
				return Equal
			}
		}}
		list := rand.Perm(count)
		for _, j := range list {
			if e := tree.Add(j); e != nil {
				t.Error(e)
			}
		}
		list = rand.Perm(count)
		for _, j := range list {
			if _, _, n := tree.Find(j); n == nil {
				t.Errorf("Should have found %d, but didn't", j)
			} else if v, ok := n.Data.(int); !ok {
				t.Errorf("Unable to cast data to int... %+v", n.Data)
			} else if v != j {
				t.Errorf("Expected to find %d, but got %d", j, v)
			}
		}
	}
}

示例#8
文件: slice_vs_map_test.go 项目: xqbumu/learn

func TestMapTo(t *testing.T) {
	func() {
		d := newSlice()
		ix := rand.Perm(testN)
		for _, v := range testVals {
			d.set(v)
		}
		for _, idx := range ix {
			d.delete(testVals[idx])
		}
		for _, idx := range ix {
			if d.exist(testVals[idx]) {
				t.Errorf("%s should have not existed!", testVals[idx])
			}
		}
	}()

	func() {
		d := newMap()
		ix := rand.Perm(testN)
		for _, v := range testVals {
			d.set(v)
		}
		for _, idx := range ix {
			d.delete(testVals[idx])
		}
		for _, idx := range ix {
			if d.exist(testVals[idx]) {
				t.Errorf("%s should have not existed!", testVals[idx])
			}
		}
	}()
}

示例#9
文件: gensparsevector_test.go 项目: philpearl/sparsevector

func genRandomGenSparseVectorInt(m int) *GenSparseVector {
	l := m * 3 / 4
	values := make([]Value, l)
	for i, v := range rand.Perm(m)[:l] {
		values[i] = Value(v)
	}
	return NewGenSparseVector(IntIndex(rand.Perm(m)[:l]), values)
}

示例#10
文件: gohammer.go 项目: dustin/gohammer

func doStuff(id int,
	res chan<- Result,
	wg *sync.WaitGroup,
	body []byte,
	prot, addr string) {

	defer wg.Done()

	localstats := [256]int64{}

	keys := make([][]byte, *nkeys / *concurrency)
	vbuckets := make([]uint16, *nvbuckets)
	for i := 0; i < len(keys); i++ {
		keys[i] = []byte(fmt.Sprintf("c%d.k%d", id, i))
		vbuckets = append(vbuckets, uint16(rand.Intn(*nvbuckets)))
	}

	client, err := memcached.Connect(prot, addr)
	if err != nil {
		log.Printf("Error connecting to %v/%v: %v", prot, addr, err)
		return
	}

	go handleResponses(client, res)

	applyLocalStats := func() {
		for j, v := range localstats {
			atomic.AddInt64(&stats[j], v)
			localstats[j] = 0
		}
	}

	cmdi := 0
	ids := rand.Perm(len(keys))
	for {
		for i, thisId := range ids {
			key := keys[thisId]
			opcode := cmds.cmds[cmdi]

			sendCommand(client, opcode, vbuckets[thisId], key, body)
			localstats[opcode]++

			if i%1000 == 0 {
				applyLocalStats()
				if atomic.LoadInt32(&isDone) == 1 {
					return
				}
			}
		}
		applyLocalStats()
		cmdi++
		if cmdi >= len(cmds.cmds) {
			cmdi = 0
			ids = rand.Perm(len(keys))
		}
	}
}

示例#11
文件: random_state.go 项目: chai2010/gocube

func RandomCubieCube() CubieCube {
	var res CubieCube

	// Generate a random permutation for the corners.
	pieces := rand.Perm(8)
	for i, x := range pieces {
		res.Corners[i].Piece = x
	}

	// Generate a random permutation for the edges.
	cornerParity := parity(pieces)
	pieces = rand.Perm(12)
	for i, x := range pieces {
		res.Edges[i].Piece = x
	}

	// Make sure the overall parity is even.
	if cornerParity != parity(pieces) {
		res.Edges[11], res.Edges[10] = res.Edges[10], res.Edges[11]
	}

	// Generate edge orientations.
	lastFlip := false
	for i := 0; i < 11; i++ {
		if rand.Intn(2) == 0 {
			lastFlip = !lastFlip
			res.Edges[i].Flip = true
		}
	}
	res.Edges[11].Flip = lastFlip

	// Generate the corner orientations.
	for i := 0; i < 7; i++ {
		res.Corners[i].Orientation = rand.Intn(3)
	}
	var orientations [8]int
	for i, x := range []int{0, 1, 5, 4, 6, 2, 3, 7} {
		orientations[i] = res.Corners[x].Orientation
	}
	for i := 0; i < 7; i++ {
		thisOrientation := orientations[i]
		nextOrientation := orientations[i+1]
		if thisOrientation == 2 {
			orientations[i+1] = (nextOrientation + 2) % 3
		} else if thisOrientation == 0 {
			orientations[i+1] = (nextOrientation + 1) % 3
		}
	}
	if orientations[7] == 0 {
		res.Corners[7].Orientation = 2
	} else if orientations[7] == 2 {
		res.Corners[7].Orientation = 0
	}

	return res
}

示例#12
文件: bst_test.go 项目: emanoelxavier/collections-cosn

func BenchmarkFind(b *testing.B) {
	bst := new(T)
	for _, i := range rand.Perm(b.N) {
		bst.Insert(i, i)
	}

	b.ResetTimer()
	for _, i := range rand.Perm(b.N) {
		bst.Find(i)
	}
}

示例#13
文件: sparsevector_test.go 项目: philpearl/sparsevector

func genRandomSparseVector(m int) *SparseVectorUint32 {
	l := m * 3 / 4
	values := make([]Value, l)
	for i, v := range rand.Perm(m)[:l] {
		values[i] = Value(v)
	}
	index := make([]uint32, l)
	for i, v := range rand.Perm(m)[:l] {
		index[i] = uint32(v)
	}
	return NewSparseVectorUint32(index, values)
}

示例#14
文件: randombagsimple.go 项目: evanh/dailyprogrammer

func main() {
	rand.Seed(time.Now().UnixNano())

	indices := rand.Perm(len(SOURCE))
	var output string
	for i := 0; i < 50; i++ {
		if i != 0 && i%7 == 0 {
			indices = rand.Perm(len(SOURCE))
		}
		output += fmt.Sprintf("%c", SOURCE[indices[i%7]])
	}
	fmt.Println(output)
}

示例#15
文件: roler.go 项目: kunthar/pachyderm

func (r *roler) openReplicaRole(shardToMasterAddress map[int]route.Address, shardToReplicaAddress map[int]map[int]route.Address) (int, int, bool) {
	for _, shard := range rand.Perm(r.sharder.NumShards()) {
		addresses := shardToReplicaAddress[shard]
		if len(addresses) < r.numReplicas && !r.hasRoleForShard(shard, shardToMasterAddress, shardToReplicaAddress) {
			for _, index := range rand.Perm(r.numReplicas) {
				if _, ok := addresses[index]; !ok {
					return shard, index, true
				}
			}
		}
	}
	return 0, 0, false
}

示例#16
文件: gensparsevector_test.go 项目: philpearl/sparsevector

func genRandomGenSparseVectorUint32(m int) *GenSparseVector {
	l := m * 3 / 4
	values := make([]Value, l)
	for i, v := range rand.Perm(m)[:l] {
		values[i] = Value(v)
	}
	index := make(Uint32Index, l)
	for i, v := range rand.Perm(m)[:l] {
		index[i] = uint32(v)
	}

	return NewGenSparseVector(index, values)
}

示例#17
文件: engine_maxflow.go 项目: hufeng03/ns_server

func buildFlowGraph(params VbmapParams) (g *Graph) {
	graphName := fmt.Sprintf("Flow graph for RI (%s)", params)
	g = NewGraph(graphName)

	tags := params.Tags.TagsList()
	tagsNodes := params.Tags.TagsNodesMap()

	maxReplicationsPerTag := 0
	if params.NumReplicas != 0 {
		maxReplicationsPerTag = params.NumSlaves / params.NumReplicas
	}

	nodes := params.Nodes()
	for _, nodeIx := range rand.Perm(len(nodes)) {
		node := nodes[nodeIx]
		nodeTag := params.Tags[node]
		nodeSrcV := NodeSourceVertex(node)
		nodeSinkV := NodeSinkVertex(node)

		g.AddEdge(Source, nodeSrcV, params.NumSlaves, params.NumSlaves)
		g.AddEdge(nodeSinkV, Sink, params.NumSlaves, 0)

		for _, tagIx := range rand.Perm(len(tags)) {
			tag := tags[tagIx]

			if tag == nodeTag {
				continue
			}

			tagNodesCount := len(tagsNodes[tag])
			tagCapacity := Min(tagNodesCount, maxReplicationsPerTag)

			tagV := TagVertex(tag)
			g.AddEdge(nodeSrcV, tagV, tagCapacity, 0)
		}
	}

	for _, tagIx := range rand.Perm(len(tags)) {
		tag := tags[tagIx]
		tagNodes := tagsNodes[tag]
		tagV := TagVertex(tag)

		for _, tagNode := range tagNodes {
			tagNodeV := NodeSinkVertex(tagNode)

			g.AddEdge(tagV, tagNodeV, params.NumSlaves, 0)
		}
	}

	return
}

示例#18
文件: binarytree_test.go 项目: quarnster/util

func TestBinaryTreeAddDelete(t *testing.T) {
	const count = 100
	const sub = 20
	for i := 0; i < 10; i++ {
		tree := Tree{Compare: func(a, b interface{}) ComparisonResult {
			aa := a.(int)
			bb := b.(int)
			switch {
			case aa < bb:
				return Less
			case aa > bb:
				return Greater
			default:
				return Equal
			}
		}}
		list := rand.Perm(count)
		for _, j := range list {
			if e := tree.Add(j); e != nil {
				t.Error(e)
			}
		}
		for k := 0; k < 10; k++ {
			list = rand.Perm(sub)
			a := rand.Intn(count - sub)
			for _, j := range list {
				if e := tree.Delete(a + j); e != nil {
					t.Error(e)
				}
			}
			list = rand.Perm(sub)
			for _, j := range list {
				if e := tree.Add(a + j); e != nil {
					t.Error(e)
				}
			}
		}

		ch := make(chan interface{})
		go func() {
			tree.Root.Walk(ch)
			close(ch)
		}()
		for j := 0; j < count; j++ {
			k := (<-ch).(int)
			if k != j {
				t.Errorf("%d != %d", k, j)
			}
		}
	}
}

示例#19
文件: sequence_test.go 项目: winsx/libnetwork

func TestRandomAllocateDeallocate(t *testing.T) {
	ds, err := randomLocalStore()
	if err != nil {
		t.Fatal(err)
	}

	numBits := int(16 * blockLen)
	hnd, err := NewHandle("bitseq-test/data/", ds, "test1", uint64(numBits))
	if err != nil {
		t.Fatal(err)
	}

	seed := time.Now().Unix()
	rand.Seed(seed)

	// Allocate all bits using a random pattern
	pattern := rand.Perm(numBits)
	for _, bit := range pattern {
		err := hnd.Set(uint64(bit))
		if err != nil {
			t.Fatalf("Unexpected failure on allocation of %d: %v.\nSeed: %d.\n%s", bit, err, seed, hnd)
		}
	}
	if hnd.Unselected() != 0 {
		t.Fatalf("Expected full sequence. Instead found %d free bits. Seed: %d.\n%s", hnd.unselected, seed, hnd)
	}
	if hnd.head.toString() != "(0xffffffff, 16)->end" {
		t.Fatalf("Unexpected db: %s", hnd.head.toString())
	}

	// Deallocate all bits using a random pattern
	pattern = rand.Perm(numBits)
	for _, bit := range pattern {
		err := hnd.Unset(uint64(bit))
		if err != nil {
			t.Fatalf("Unexpected failure on deallocation of %d: %v.\nSeed: %d.\n%s", bit, err, seed, hnd)
		}
	}
	if hnd.Unselected() != uint64(numBits) {
		t.Fatalf("Expected full sequence. Instead found %d free bits. Seed: %d.\n%s", hnd.unselected, seed, hnd)
	}
	if hnd.head.toString() != "(0x0, 16)->end" {
		t.Fatalf("Unexpected db: %s", hnd.head.toString())
	}

	err = hnd.Destroy()
	if err != nil {
		t.Fatal(err)
	}
}

示例#20
文件: set_test.go 项目: geoah/cookiejar

func BenchmarkRemove(b *testing.B) {
	// Create some initial data and fill the set
	data := rand.Perm(b.N)
	set := New()
	for _, val := range data {
		set.Insert(val)
	}
	// Execute the benchmark (different order)
	rems := rand.Perm(b.N)
	b.ResetTimer()
	for _, val := range rems {
		set.Remove(val)
	}
}

示例#21
文件: llrb_test.go 项目: zotebook/GoLLRB

func TestRandomReplace(t *testing.T) {
	tree := New(NaturalSortLessInt)
	n := 100
	perm := rand.Perm(n)
	for i := 0; i < n; i++ {
		tree.ReplaceOrInsert(Int(perm[i]))
	}
	perm = rand.Perm(n)
	for i := 0; i < n; i++ {
		if replaced := tree.ReplaceOrInsert(Int(perm[i])); replaced == nil || replaced.(Int) != Int(perm[i]) {
			t.Errorf("error replacing")
		}
	}
}

示例#22
文件: llrb_test.go 项目: prataprc/golib

func TestRandomReplace(t *testing.T) {
	tree := NewLLRB()
	n := 100
	perm := rand.Perm(n)
	for i := 0; i < n; i++ {
		tree.Upsert(&KeyInt{int64(perm[i]), -1})
	}
	perm = rand.Perm(n)
	for i := 0; i < n; i++ {
		replaced := tree.Upsert(&KeyInt{int64(perm[i]), -1})
		if replaced == nil || replaced.(*KeyInt).Key != int64(perm[i]) {
			t.Errorf("error replacing")
		}
	}
}

示例#23
文件: pathfinding_test.go 项目: vinicius-ianni/gopathfinding

//Generate a random MapData given some dimensions
func generate_map(n int) *MapData {
	map_data := *NewMapData(n, n)
	map_data[0][0] = START
	map_data[n-1][n-1] = STOP

	xs := rand.Perm(n - 1)
	ys := rand.Perm(n - 1)

	for i := 1; i < len(xs); i += rand.Intn(4) + 1 {
		for j := 1; j < len(ys); j++ {
			map_data[xs[i]][ys[j]] = WALL
		}
	}
	return &map_data
}

示例#24
文件: llrb_test.go 项目: go2mobi/GoLLRB

func TestRandomReplace(t *testing.T) {
	tree := New()
	n := 100
	perm := rand.Perm(n)
	for i := 0; i < n; i++ {
		tree.ReplaceOrInsert(uint64(perm[i]))
	}
	perm = rand.Perm(n)
	for i := 0; i < n; i++ {
		v := uint64(perm[i])
		if replaced := tree.ReplaceOrInsert(v); !replaced {
			t.Errorf("error replacing")
		}
	}
}

示例#25
文件: map_to_slice_vs_map_test.go 项目: xqbumu/learn

func BenchmarkExist(b *testing.B) {
	b.StopTimer()
	var d Interface
	if opt == "slice" {
		d = newMapToSlice()
	} else {
		d = newMapToMap()
	}
	k := "A"
	for _, v := range testVals {
		d.set(k, v)
	}

	// to make it not biased towards data structures
	// with an order, such as slice.
	ix := rand.Perm(testN)

	b.StartTimer()
	b.ReportAllocs()

	for _, idx := range ix {
		if !d.exist(k, testVals[idx]) {
			b.Errorf("%s should have existed!", testVals[idx])
		}
	}
}

示例#26
文件: scan.go 项目: XiliangSong/gscan

func (options *ScanOptions) SSLMatchHosts(conn *tls.Conn) []string {
	hosts := make([]string, 0)
	options.hostsMutex.Lock()
	for _, host := range options.inputHosts {
		testhost := host.Host
		if strings.Contains(testhost, ".appspot.com") {
			testhost = "appengine.google.com"
		} else if strings.Contains(testhost, "ggpht.com") {
			testhost = "googleusercontent.com"
		} else if strings.Contains(testhost, ".books.google.com") {
			testhost = "books.google.com"
		} else if strings.Contains(testhost, ".googleusercontent.com") {
			testhost = "googleusercontent.com"
		}
		if conn.VerifyHostname(testhost) == nil {
			hosts = append(hosts, host.Host)
		}
	}
	options.hostsMutex.Unlock()
	dest := make([]string, len(hosts))
	perm := rand.Perm(len(hosts))
	for i, v := range perm {
		dest[v] = hosts[i]
	}
	hosts = dest
	return hosts
}

示例#27
文件: generate.go 项目: pshrmn/golf-simulator

func Generate(name string) Course {
	holes := make([]Hole, 18)
	for index, pos := range rand.Perm(18) {
		holes[index] = GenerateHole(pars[pos])
	}
	return Course{Name: name, Par: 72, Holes: holes}
}

示例#28
文件: main.go 项目: lukamicoder/myip

func getExternalIP() net.IP {
	var currentIP net.IP
	for _, i := range rand.Perm(len(urls)) {
		if verbose {
			fmt.Printf("Connecting to %v...\n", urls[i])
		}

		url := "http://" + urls[i]

		content, err := getResponse(url)
		if err != nil {
			if verbose {
				fmt.Printf("%v\n", err)
			}
			continue
		}

		ip := regex.FindString(content)

		currentIP = net.ParseIP(ip)

		if currentIP != nil {
			return currentIP
		}

		fmt.Println("No valid IP address could be parsed from response.")
	}

	return currentIP
}

示例#29
文件: binary-tree_test.go 项目: kshvakov/go-to-Go

func TestBinaryTreeDelete(t *testing.T) {

	keys := rand.Perm(5217)

	tree := new(BinaryTree)

	for _, i := range keys {

		tree.Set(i, fmt.Sprintf("format_%d", i))
	}

	for _, i := range keys {

		if _, err := tree.Get(i); err != nil {

			t.Error(err.Error())
		}
	}

	for _, i := range keys {

		tree.Delete(i)

		if _, err := tree.Get(i); err == nil {

			t.Error("Найдено, а не должно бы")
		}
	}
}

示例#30
文件: pingit_recvit.go 项目: lukegb/Stripe-CTF-2.0

func generatePermSet(mode int) []int {
	if mode == 0 {
		return rand.Perm(1000)
	}

	return make([]int, 0)
}

展开阅读全文