示例#1
0
func TestRandomReplace(t *testing.T) {
        tree := New(IntLess)
        n := 100
        perm := rand.Perm(n)
        for i := 0; i < n; i++ {
                tree.ReplaceOrInsert(perm[i])
        }
        perm = rand.Perm(n)
        for i := 0; i < n; i++ {
                if replaced := tree.ReplaceOrInsert(perm[i]); replaced == nil || replaced.(int) != perm[i] {

                        t.Errorf("error replacing")
                }
        }
}
示例#2
0
func main() {
	rand.Seed(time.Seconds())
	nums := rand.Perm(MAX)[:COUNT]
	for _, val := range nums {
		fmt.Println(val)
	}
}
// New returns a new, random binary tree holding the values k, 2k, ..., 10k.
func New(k int) *Tree {
	var t *Tree
	for _, v := range rand.Perm(10) {
		t = insert(t, (1+v)*k)
	}
	return t
}
示例#4
0
func main() {
	n := 10000
	vrand := rand.Perm(n)
	vinc := make([]int, n)
	for i := range vinc {
		vinc[i] = i
	}
	vdec := make([]int, n)
	for i := range vdec {
		vdec[i] = i
	}

	if !CheckInsertsAndDeletes(vrand) {
		fmt.Printf("Failed inserts and deletes when done in random order.\n")
	}
	if !CheckQueries(vrand) {
		fmt.Printf("Failed queries when done in random order.\n")
	}

	if !CheckInsertsAndDeletes(vinc) {
		fmt.Printf("Failed inserts and deletes when done in increasing order.\n")
	}
	if !CheckQueries(vinc) {
		fmt.Printf("Failed queries when done in increasing order.\n")
	}

	if !CheckInsertsAndDeletes(vdec) {
		fmt.Printf("Failed inserts and deletes when done in decreasing order.\n")
	}
	if !CheckQueries(vdec) {
		fmt.Printf("Failed queries when done in decreasing order.\n")
	}
}
示例#5
0
func TestRandomInsertDeleteNonExistent(t *testing.T) {
        tree := New(IntLess)
        n := 100
        perm := rand.Perm(n)
        for i := 0; i < n; i++ {
                tree.ReplaceOrInsert(perm[i])
        }
        if tree.Delete(200) != nil {
                t.Errorf("deleted non-existent item")
        }
        if tree.Delete(-2) != nil {
                t.Errorf("deleted non-existent item")
        }
        for i := 0; i < n; i++ {
                if u := tree.Delete(i); u == nil || u.(int) != i {
                        t.Errorf("delete failed")
                }
        }
        if tree.Delete(200) != nil {
                t.Errorf("deleted non-existent item")
        }
        if tree.Delete(-2) != nil {
                t.Errorf("deleted non-existent item")
        }
}
示例#6
0
func main() {
	names := []string{
		"Unique Inserts",
		"Repeated Inserts",
		"Unique Deletes",
		"Repeated Deletes",
		"Queries",
	}

	d := rand.Perm(N)
	total := Bench(d)
	for i := 1; i < R; i++ {
		times := Bench(d)
		for j := range times {
			total[j] += times[j]
		}
	}
	for i := range total {
		total[i] /= float(R)
	}

	fmt.Printf("Using input size %d and averaged over %d runs.\n", N, R)
	fmt.Printf("%3.3f:\t%d\t%s\n", total[0], N, names[0])
	fmt.Printf("%3.3f:\t%d\t%s\n", total[1], N, names[1])
	fmt.Printf("%3.3f:\t%d\t%s\n", total[2], N/2, names[2])
	fmt.Printf("%3.3f:\t%d\t%s\n", total[3], N/2, names[3])
	fmt.Printf("%3.3f:\t%d\t%s\n", total[4], N, names[4])
}
func randomString() string {
	alphabets := "abcdefghijklmnopqrstuvwxyz"
	intArray := rand.Perm(len(alphabets))
	rstring := strings.Map(func(i int) int { return int(alphabets[intArray[i%26]]) },
		alphabets)
	return rstring
}
示例#8
0
// This test checks that the hash tree is always the same
// no matter in which order the IDs are being inserted
func TestHashTree1(t *testing.T) {
	set := []string{}
	for i := 0; i < 1000; i++ {
		set = append(set, fmt.Sprintf("m%v", i))
	}
	hash := ""
	for test := 0; test < 1000; test++ {
		tree := NewSimpleHashTree()
		perm := rand.Perm(len(set))
		for i := 0; i < len(set); i++ {
			member := set[perm[i]]
			h := sha256.New()
			h.Write([]byte(member))
			tree.Add(hex.EncodeToString(h.Sum()))
		}
		result := tree.Hash()
		if test == 0 {
			hash = result
		} else {
			if hash != result {
				t.Fatal("Hashes are not the same")
			}
		}
	}
}
示例#9
0
func main() {
	runtime.GOMAXPROCS(12) //max number of processes for concurrency
	for i := 1; i < 7; i++ {
		done := make(chan sort.Algorithm) //channel for communication
		nums := rand.Perm(1000 * i)
		println("\nusing", 1*graph.Pow(10, i), "elements")
		nums1, nums2 := make([]int, len(nums)), make([]int, len(nums))
		copy(nums1, nums) //create copies of the array for others to sort
		copy(nums2, nums)
		go sort.TimeEvent(sort.InsertionSort, nums, "Insertion Sort", done)
		go sort.TimeEvent(sort.QuickSort, nums1, "Quick Sort", done)
		go sort.TimeEvent(sort.TreeSort, nums2, "Tree Sort", done)
		n := 0
		for alg := range done { //wait for the events to finish execution
			println(alg.Name, "finished in", alg.Time)
			switch alg.Name {
			case "Insertion Sort":
				insertionVals.Y[i] = alg.Time
			case "Quick Sort":
				quickVals.Y[i] = alg.Time
			case "Tree Sort":
				treeVals.Y[i] = alg.Time
			}
			n++
			if n > 2 {
				close(done)
			} //close the channel
		}
	}
	values := []graph.Values{treeVals, insertionVals, quickVals}
	graph.DrawToFile("output.svg", graph.NewGraph(100, 100, values))
}
示例#10
0
文件: gnmb.go 项目: kicool/kicool.go
func generate() *guess {
	rand.Seed(time.Nanoseconds())
	rnd := rand.Perm(10)
	tmp := new(guess)
	for i := range tmp.nmbr {
		tmp.nmbr[i] = rnd[i]
	}
	return tmp
}
示例#11
0
func BenchmarkDelete(b *testing.B) {
	b.StopTimer()
	ints := rand.Perm(b.N)
	tree := treeOfInts(ints)

	b.StartTimer()
	for i := 0; i < b.N; i++ {
		tree.Delete(i)
	}
}
示例#12
0
func TestRandomInsertSequentialDelete(t *testing.T) {
        tree := New(IntLess)
        n := 1000
        perm := rand.Perm(n)
        for i := 0; i < n; i++ {
                tree.ReplaceOrInsert(perm[i])
        }
        for i := 0; i < n; i++ {
                tree.Delete(i)
        }
}
示例#13
0
func BenchmarkLookup(b *testing.B) {
	b.StopTimer()
	ints := rand.Perm(b.N)
	tree := treeOfInts(ints)
	b.StartTimer()
	for j := 0; j < 10; j++ {
		for i := 0; i < len(ints)/10; i++ {
			_ = tree.Exists(ints[i])
		}
	}
}
示例#14
0
func TestRandomInsertStats(t *testing.T) {
        tree := New(IntLess)
        n := 100000
        perm := rand.Perm(n)
        for i := 0; i < n; i++ {
                tree.ReplaceOrInsert(perm[i])
        }
        avg, _ := tree.HeightStats()
        expAvg := math.Log2(float64(n)) - 1.5
        if math.Fabs(avg-expAvg) >= 2.0 {
                t.Errorf("too much deviation from expected average height")
        }
}
示例#15
0
func TestRandomInsertOrder(t *testing.T) {
        tree := New(IntLess)
        n := 1000
        perm := rand.Perm(n)
        for i := 0; i < n; i++ {
                tree.ReplaceOrInsert(perm[i])
        }
        c := tree.IterAscend()
        for j, item := 0, <-c; item != nil; j, item = j+1, <-c {
                if item.(int) != j {
                        t.Fatalf("bad order")
                }
        }
}
示例#16
0
文件: poker.go 项目: hjfreyer/misc
func RunHands() map[CardPair]Stats {
	d := Deck()
	result := make(map[CardPair]Stats)

	for i := 0; i < HANDS; i++ {
		d2 := make([]Card, 52)

		for i, p := range rand.Perm(52) {
			d2[i] = d[p]
		}

		RunHand(d2, result)
	}
	return result
}
示例#17
0
文件: tsp.go 项目: tzok/go-tsp
func random(matrix [][]int) (tour []int, best int) {
	const maxIters = 1e6

	best = 1e6
	for i := 0; i < maxIters; i++ {
		perm := rand.Perm(len(matrix))
		length := matrix[perm[len(matrix)-1]][perm[0]]
		for j := 1; j < len(matrix); j++ {
			length += matrix[perm[j-1]][perm[j]]
		}
		if length < best {
			tour, best = perm, length
		}
	}
	return
}
示例#18
0
func TestInsertNoReplace(t *testing.T) {
        tree := New(IntLess)
        n := 1000
        for q := 0; q < 2; q++ {
                perm := rand.Perm(n)
                for i := 0; i < n; i++ {
                        tree.InsertNoReplace(perm[i])
                }
        }
        c := tree.IterAscend()
        for j, item := 0, <-c; item != nil; j, item = j+1, <-c {
                if item.(int) != j/2 {
                        t.Fatalf("bad order")
                }
        }
}
示例#19
0
文件: keno.go 项目: lericson/go-keno
// Other way to simulate movement, more random-seeming
func (juggle *Juggle) smackAroundBalls() []int {
	var numHits = juggle.size / numRotorBlades
	hits := make([]int, numHits)
	for _, i := range rand.Perm(numHits) {
		select {
		case ball := <-juggle.ballsInCage:
			hits[i] = ball
		default:
			break
		}
	}
	for _, ball := range hits {
		juggle.ballsInCage <- ball
	}
	return hits
}
示例#20
0
func TestEquals(t *testing.T) {
	a := rand.Perm(1000)
	tree1 := NewIntTree()
	tree2 := NewIntTree()
	for _, i := range a {
		tree1.Insert(i)
		tree2.Insert(i)
	}
	if !tree1.equals(tree2) {
		t.Errorf("equals returned false")
	}

	tree2.Remove(tree2.Last())
	if tree1.equals(tree2) {
		t.Errorf("equals returned true")
	}
}
示例#21
0
func TestRandomInsertPartialDeleteOrder(t *testing.T) {
        tree := New(IntLess)
        n := 100
        perm := rand.Perm(n)
        for i := 0; i < n; i++ {
                tree.ReplaceOrInsert(perm[i])
        }
        for i := 1; i < n-1; i++ {
                tree.Delete(i)
        }
        c := tree.IterAscend()
        if (<-c).(int) != 0 {
                t.Errorf("expecting 0")
        }
        if (<-c).(int) != n-1 {
                t.Errorf("expecting %d", n-1)
        }
}
示例#22
0
func TestBuild(t *testing.T) {
	m7a := Mutation{ID: "m7a"}
	m7b := Mutation{ID: "m7b"}
	m8a := Mutation{ID: "m8a"}
	m8b := Mutation{ID: "m8b"}
	m9a := Mutation{ID: "m9a"}
	m9b := Mutation{ID: "m9b"}
	m7 := Mutation{ID: "m7", Dependencies: []string{"m7a", "m7b"}}
	m8 := Mutation{ID: "m8", Dependencies: []string{"m8a", "m8b"}}
	m9 := Mutation{ID: "m9", Dependencies: []string{"m9a", "m9b"}}
	m11 := Mutation{ID: "m11", Dependencies: []string{"m9b"}}
	m5 := Mutation{ID: "m5", Dependencies: []string{"m7", "m8"}}
	m6 := Mutation{ID: "m6", Dependencies: []string{"m8", "m9", "m11"}}
	m10 := Mutation{ID: "m10", Dependencies: []string{"m9b"}}
	m1 := Mutation{ID: "m1", Dependencies: []string{"m5"}}
	m2 := Mutation{ID: "m2", Dependencies: []string{"m5"}}
	m3 := Mutation{ID: "m3", Dependencies: []string{"m5", "m6"}}
	m4 := Mutation{ID: "m4", Dependencies: []string{"m6", "m10"}}
	muts := []Mutation{m1, m2, m3, m4, m5, m6, m10, m7, m8, m9, m11, m7a, m7b, m8a, m8b, m9a, m9b}

	// Try to apply the mutations in all possible permutations
	for i := 0; i < 10000; i++ {
		perm := rand.Perm(len(muts))
		b := NewSimpleBuilder()
		for i := 0; i < len(muts); i++ {
			mut := muts[perm[i]]
			_, err := Build(b, mut)
			if err != nil {
				t.Fatal(err.String())
				return
			}
		}

		if len(muts) != len(b.AppliedMutationIDs()) {
			t.Fatal("Not all mutations have been applied")
		}
	}
}
示例#23
0
文件: MyBot.go 项目: B-Rich/ants
//DoTurn is where you should do your bot's actual work.
func (mb *MyBot) DoTurn(s *State) os.Error {
	dirs := []Direction{North, East, South, West}
	for loc, ant := range s.Map.Ants {
		if ant != MY_ANT {
			continue
		}

		//try each direction in a random order
		p := rand.Perm(4)
		for _, i := range p {
			d := dirs[i]

			loc2 := s.Map.Move(loc, d)
			if s.Map.SafeDestination(loc2) {
				s.IssueOrderLoc(loc, d)
				//there's also an s.IssueOrderRowCol if you don't have a Location handy
				break
			}
		}
	}
	//returning an error will halt the whole program!
	return nil
}
示例#24
0
文件: poker.go 项目: hjfreyer/misc
func CompareHands() {
	d := Deck()
	d2 := make([]Card, 52)

	for i, p := range rand.Perm(52) {
		d2[i] = d[p]
	}
	hand1, hand2 := d2[:7], d2[7:14]

	sort.Sort(CardSort(hand1))
	sort.Sort(CardSort(hand2))

	cmp := CmpHand(BestOfSeven(hand1), BestOfSeven(hand2))
	var symbol byte
	switch {
	case cmp == 0:
		symbol = '='
	case cmp < 0:
		symbol = '<'
	case cmp > 0:
		symbol = '>'
	}
	fmt.Printf("%s %c %s\n\n", hand1, symbol, hand2)
}
示例#25
0
// state 2 - Build and train test set
func interactiveBuildTrainAndTestSet() {
	var (
		err         os.Error
		inputString string
		inputInt    int
	)
	// STEP 1:
	// Begin building training and test set
	fmt.Println("Building train and test set")
	inputString = promptString("filename", "What file would you like to split?")
	debugMsg("Opening file: %s", inputString)
	// Open the file for reading
	dataFile, err := os.Open(inputString)
	errCheck(err)
	// We do not need this file after, so close it upon leaving this method
	defer dataFile.Close()
	// Create a buffered reader for the file
	dataReader := bufio.NewReader(dataFile)
	var line string

	// STEP 2:
	// Create a map for storing the temporary files

	tempFileMap := map[string]*os.File{}
	countMap := map[string]int{}
	var exists bool       // For checking if element exists
	var tempFile *os.File // Place holder for the temporary file
	// which is to be put in the map.
	for line, err = dataReader.ReadString('\n'); // read line by line
	err == nil;                                  // stop on error
	line, err = dataReader.ReadString('\n') {
		// Take each instance and write it to a label specific file
		line = strings.Trim(line, "\n")
		feature := strings.Split(line, ",")
		label := feature[len(feature)-1]
		tempFile, exists = tempFileMap[label]
		countMap[label]++
		if exists {
			// Write to the file
			_, err = tempFile.WriteString(line + "\n")
			errCheck(err)
		} else {
			// Create the file and write the line
			tempFileName := dataFile.Name() + "." + label + ".tmp"
			debugMsg("Creating temporary file: %s", tempFileName)
			tempFile, err := os.OpenFile(
				tempFileName,
				os.O_CREATE+os.O_WRONLY+os.O_TRUNC,
				0666)
			tempFileMap[label] = tempFile
			defer tempFile.Close()
			defer os.Remove(tempFileName)
			_, err = tempFile.WriteString(line + "\n")
			errCheck(err)
		}
	}
	// Close and re-open the files as readable
	debugMsg("Closing all temporary files for writing. Re-opening as read-only.")
	for k, v := range tempFileMap {
		fileName := v.Name()
		v.Close()
		tempFileMap[k], err = os.Open(fileName)
		errCheck(err)
		// We do not need this file after, so close it upon leaving this method
		defer tempFileMap[k].Close()
	}

	// STEP 3:
	// Receive the number of each label (class) we'd like to add to the training
	// set

	// Hold the amount of each label we'd like in the training set in a map
	trainCountMap := map[string]int{}
	fmt.Println("Please enter the number of each type of label you'd",
		"like in the training set.")
	// Ask user how much of each label they want and put it in a map
	// trainCountMap
	for k, v := range countMap {
		inputInt = promptInt(k, "label: %s max: %d", k, v)
		trainCountMap[k] = inputInt
	}
	debugMsg("Creating: %s", dataFile.Name()+".train")
	// Open a file for writing training data
	trainFile, err := os.OpenFile(
		dataFile.Name()+".train",
		os.O_CREATE+os.O_WRONLY+os.O_TRUNC,
		0666)
	errCheck(err)
	// We do not need this file after, so close it upon leaving this method
	defer trainFile.Close()
	// STEP 4:
	// Read the correct amount of each label in

	for k, v := range trainCountMap {
		debugMsg("label: %s count: %d", k, v)
		dataReader := bufio.NewReader(tempFileMap[k])
		// Open a file for writing testing data
		testFile, err := os.OpenFile(
			dataFile.Name()+"."+k+".test",
			os.O_CREATE+os.O_WRONLY+os.O_TRUNC,
			0666)
		errCheck(err)
		// We do not need this file after, so close it upon leaving this method
		defer testFile.Close()

		if v > 0 {
			// Generate a random permuation
			var randomized sort.IntSlice
			randomized = rand.Perm(countMap[k])
			// use a slice the first /v/ of them
			randomized = randomized[0:v]
			// sort the ints so that as we iterate through each instance we can
			// easily find the next one we need to export
			randomized.Sort()
			// Read through the file, writing the included instances to
			// .train and the others to .test
			lineCount := 0
			if len(randomized) > 0 {
				for line, err = dataReader.ReadString('\n'); // read line by line
				err == nil;                                  // stop on error
				line, err = dataReader.ReadString('\n') {
					if lineCount == randomized[0] {
						_, err = trainFile.WriteString(line)
						errCheck(err)
						if len(randomized) > 1 {
							randomized = randomized[1:len(randomized)]
						} else {
							randomized[0] = -1 // skip the rest
						}
					} else {
						_, err = testFile.WriteString(line)
						errCheck(err)
					}
					lineCount++
				}
			} else {

			}
		} else {
			//TODO: Add a handler for -1
			// None of the label were requested in the training set, so dump to test
			for line, err = dataReader.ReadString('\n'); // read line by line
			err == nil;                                  // stop on error
			line, err = dataReader.ReadString('\n') {
				_, err = testFile.WriteString(line)
				errCheck(err)
			}
		}
		testFile.Close()
	}
	fmt.Println()
}
示例#26
0
func BenchmarkInsert(b *testing.B) {
	b.StopTimer()
	ints := rand.Perm(b.N)
	b.StartTimer()
	_ = treeOfInts(ints)
}
示例#27
0
func TestRandomTree(t *testing.T) {
	a := rand.Perm(1000)
	verifyTreeWithRandomData(a, t)
}