예제 #1
0
파일: sort-1.go 프로젝트: jaymecd/go-tests
func main() {

	// Sort methods are specific to the builtin type;
	// here's an example for strings. Note that sorting is
	// in-place, so it changes the given slice and doesn't
	// return a new one.
	strs := []string{"c", "a", "b"}

	// We can also use `sort` to check if a slice is
	// already in sorted order.
	fmt.Println("Strings:", strs)
	fmt.Println("Sorted: ", sort.StringsAreSorted(strs))

	sort.Strings(strs)

	fmt.Println("Strings:", strs)
	fmt.Println("Sorted: ", sort.StringsAreSorted(strs))

	fmt.Println()

	// An example of sorting `int`s.
	ints := []int{7, 2, 4}

	fmt.Println("Ints:   ", ints)
	fmt.Println("Sorted: ", sort.IntsAreSorted(ints))

	sort.Ints(ints)

	fmt.Println("Ints:   ", ints)
	fmt.Println("Sorted: ", sort.IntsAreSorted(ints))
}
예제 #2
0
// testSortArguments runs a given sort function with the most
// basic of input sequences in order to test its robustness.
func testSortArguments(t *testing.T, f func([]string)) {
	// these should silently do nothing
	f(nil)
	f(make([]string, 0))
	f([]string{"a"})
	// test the bare minimum input, two elements
	input := []string{"b", "a"}
	f(input)
	if !sort.StringsAreSorted(input) {
		t.Error("two inputs not sorted")
	}
	// now try three elements
	input = []string{"c", "b", "a"}
	f(input)
	if !sort.StringsAreSorted(input) {
		t.Error("three inputs not sorted")
	}
	// test with all empty input
	input = []string{"", "", "", "", "", "", "", "", "", ""}
	f(input)
	// test with peculiar input
	input = []string{"z", "m", "", "a", "d", "tt", "tt", "tt", "foo", "bar"}
	f(input)
	if !sort.StringsAreSorted(input) {
		t.Error("peculiar inputs not sorted")
	}
}
예제 #3
0
func TestMergeString(t *testing.T) {
	l := SortedString(10)
	for !sort.StringsAreSorted(l) {
		t.Errorf("Not sorted: [%v]\n", l)
	}
	for i := 0; i < 5000; i++ {
		s := UniqueString(rand.Intn(11))
		l = mergeString(l, s)
		if !sort.StringsAreSorted(l) {
			t.Error("Strings are not sorted")
			t.FailNow()
		}
	}
}
예제 #4
0
func TestDataKey(t *testing.T) {
	var uid uint64
	for uid = 0; uid < 1001; uid++ {
		sattr := fmt.Sprintf("attr:%d", uid)
		key := DataKey(sattr, uid)
		pk := Parse(key)

		require.True(t, pk.IsData())
		require.Equal(t, sattr, pk.Attr)
		require.Equal(t, uid, pk.Uid)
	}

	keys := make([]string, 0, 1024)
	for uid = 1024; uid >= 1; uid-- {
		key := DataKey("testing.key", uid)
		keys = append(keys, string(key))
	}
	// Test that sorting is as expected.
	sort.Strings(keys)
	require.True(t, sort.StringsAreSorted(keys))
	for i, key := range keys {
		exp := DataKey("testing.key", uint64(i+1))
		require.Equal(t, string(exp), key)
	}
}
예제 #5
0
func TestEverything(t *testing.T) {
	m := make(map[string]*Flag)
	desired := "0"
	visitor := func(f *Flag) {
		if len(f.Name) > 5 && f.Name[0:5] == "test_" {
			m[f.Name] = f
			ok := false
			switch {
			case f.Value.String() == desired:
				ok = true
			case f.Name == "test_bool" && f.Value.String() == boolString(desired):
				ok = true
			case f.Name == "test_duration" && f.Value.String() == desired+"s":
				ok = true
			}
			if !ok {
				t.Error("Visit: bad value", f.Value.String(), "for", f.Name)
			}
		}
	}
	VisitAll(visitor)
	if len(m) != 9 {
		t.Error("VisitAll misses some flags")
		for k, v := range m {
			t.Log(k, *v)
		}
	}
	m = make(map[string]*Flag)
	Visit(visitor)
	if len(m) != 0 {
		t.Errorf("Visit sees unset flags")
		for k, v := range m {
			t.Log(k, *v)
		}
	}
	// Now set all flags
	Set("test_bool", "true")
	Set("test_int", "1")
	Set("test_int64", "1")
	Set("test_uint", "1")
	Set("test_uint64", "1")
	Set("test_string", "1")
	Set("test_float64", "1")
	Set("test_duration", "1s")
	Set("test_optional_int", "1")
	desired = "1"
	Visit(visitor)
	if len(m) != 9 {
		t.Error("Visit fails after set")
		for k, v := range m {
			t.Log(k, *v)
		}
	}
	// Now test they're visited in sort order.
	var flagNames []string
	Visit(func(f *Flag) { flagNames = append(flagNames, f.Name) })
	if !sort.StringsAreSorted(flagNames) {
		t.Errorf("flag names not sorted: %v", flagNames)
	}
}
예제 #6
0
func (bmt byModTime) Less(i, j int) bool {
	// If the creation times are identical, sort by filename (pid) instead.
	if bmt[i].ModTime() == bmt[j].ModTime() {
		return sort.StringsAreSorted([]string{bmt[i].Name(), bmt[j].Name()})
	}
	return bmt[i].ModTime().UnixNano() < bmt[j].ModTime().UnixNano()
}
예제 #7
0
파일: da.go 프로젝트: sugyan/go-zenra-bot
// BuildWithIDs constructs a double array from given keywords and ids.
func BuildWithIDs(keywords []string, ids []int) (DoubleArray, error) {
	d := DoubleArray{}
	d.init()
	if len(keywords) != len(ids) {
		return d, fmt.Errorf("invalid arguments")
	}
	if len(keywords) == 0 {
		return d, nil
	}
	if !sort.StringsAreSorted(keywords) {
		h := make(map[string]int)
		for i, key := range keywords {
			h[key] = ids[i]
		}
		sort.Strings(keywords)
		ids = ids[:0]
		for _, key := range keywords {
			ids = append(ids, h[key])
		}
	}
	branches := make([]int, len(keywords))
	for i := range keywords {
		branches[i] = i
	}
	d.add(0, 0, branches, keywords, ids)
	d.truncate()
	return d, nil
}
예제 #8
0
// BuildIndexTable constructs a index table from keywords.
func BuildIndexTable(sortedKeywords []string) (IndexTable, error) {
	idx := IndexTable{Dup: map[int32]int32{}}
	if !sort.StringsAreSorted(sortedKeywords) {
		return idx, fmt.Errorf("unsorted keywords")
	}
	keys := make([]string, 0, len(sortedKeywords))
	ids := make([]int, 0, len(sortedKeywords))
	prev := struct {
		no   int
		word string
	}{}
	for i, key := range sortedKeywords {
		if key == prev.word {
			idx.Dup[int32(prev.no)]++
			continue
		}
		prev.no = i
		prev.word = key
		keys = append(keys, key)
		ids = append(ids, i)
	}
	d, err := da.BuildWithIDs(keys, ids)
	if err != nil {
		return idx, fmt.Errorf("build error, %v", err)
	}
	idx.Da = d
	return idx, nil
}
예제 #9
0
func TestStrings(t *testing.T) {
	data := strings
	Sort(sort.StringSlice(data[0:]))
	if !sort.StringsAreSorted(data[0:]) {
		t.Errorf("sorted %v", strings)
		t.Errorf("   got %v", data)
	}
}
예제 #10
0
func stringSlicesEqual(x, y []string) bool {
	if len(x) != len(y) {
		return false
	}
	if !sort.StringsAreSorted(x) {
		sort.Strings(x)
	}
	if !sort.StringsAreSorted(y) {
		sort.Strings(y)
	}
	for i := range x {
		if x[i] != y[i] {
			return false
		}
	}
	return true
}
예제 #11
0
// Contains returns whether the slice contains a string
func (s Strings) Contains(a string) bool {
	if !sort.StringsAreSorted(s) {
		sort.Strings(s)
	}

	i := sort.SearchStrings(s, a)
	return i < len(s) && s[i] == a
}
예제 #12
0
// testSortRepeatedCycle generates a repeating cycle of strings and
// runs the given sort on that data. The size is the number of elements
// to generate for the test.
func testSortRepeatedCycle(t *testing.T, f func([]string), size int) {
	checkTestSize(t, size)
	input := make([]string, size)
	copy(input, repeatedCycleStrings)
	f(input)
	if !sort.StringsAreSorted(input) {
		t.Error("repeated cycle input not sorted")
	}
}
예제 #13
0
// testSortNonUnique runs the given sort function on a set of words
// that are not necessarily unique (many will repeat a random number
// of times).
func testSortNonUnique(t *testing.T, f func([]string), size int) {
	checkTestSize(t, size)
	input := make([]string, size)
	copy(input, nonUniqueWords)
	f(input)
	if !sort.StringsAreSorted(input) {
		t.Error("non-unique words input not sorted")
	}
}
예제 #14
0
파일: fakedb_test.go 프로젝트: dushmis/go
func TestDrivers(t *testing.T) {
	unregisterAllDrivers()
	Register("test", fdriver)
	Register("invalid", Dummy{})
	all := Drivers()
	if len(all) < 2 || !sort.StringsAreSorted(all) || !contains(all, "test") || !contains(all, "invalid") {
		t.Fatalf("Drivers = %v, want sorted list with at least [invalid, test]", all)
	}
}
예제 #15
0
// testSortRandom runs the given sort on a randomly generated data set
// consisting of strings of 100 letters and upper and lower case letters.
func testSortRandom(t *testing.T, f func([]string), size int) {
	checkTestSize(t, size)
	input := make([]string, size)
	copy(input, randomStrings)
	f(input)
	if !sort.StringsAreSorted(input) {
		t.Error("random input not sorted")
	}
}
예제 #16
0
// testSortSorted runs the given sort function on an input set that
// is already in sorted order.
func testSortSorted(t *testing.T, f func([]string), size int) {
	checkTestSize(t, size)
	input := make([]string, size)
	copy(input, uniqueWords)
	sort.Strings(input)
	f(input)
	if !sort.StringsAreSorted(input) {
		t.Error("sorted dictwords input not sorted")
	}
}
예제 #17
0
파일: main.go 프로젝트: josvazg/algorithms
func main() {
	for _, u := range tests {
		list := make([]int, len(u))
		//fmt.Println("Unsorted:", u)
		for _, asort := range sorts {
			copy(list, u)
			asort.fn(list)
			//fmt.Println(asort.name, " sorted list:", list)
			if !sort.IntsAreSorted(list) {
				fmt.Println("FAILED! list=", list)
				os.Exit(-1)
			}
		}
	}
	fmt.Println("PASSED")
	times := 50000
	for _, asort := range sorts {
		t := time.Now()
		for i := 0; i < times; i++ {
			for _, u := range tests {
				list := make([]int, len(u))
				copy(list, u)
				asort.fn(list)
			}
		}
		fmt.Println(asort.name, "sorted", times, "times in", time.Since(t))
	}
	fmt.Println("Strings tests")
	teststr := convert(tests)
	for _, u := range teststr {
		list := make([]string, len(u))
		//fmt.Println("Unsorted:", u)
		for _, asort := range sortstr {
			copy(list, u)
			asort.fn(list)
			//fmt.Println(asort.name, " sorted list:", list)
			if !sort.StringsAreSorted(list) {
				fmt.Println("FAILED!")
				os.Exit(-1)
			}
		}
	}
	fmt.Println("PASSED")
	for _, asort := range sortstr {
		t := time.Now()
		for i := 0; i < times; i++ {
			for _, u := range teststr {
				list := make([]string, len(u))
				copy(list, u)
				asort.fn(list)
			}
		}
		fmt.Println(asort.name, " sorted", times, "times in", time.Since(t))
	}
}
예제 #18
0
파일: utils.go 프로젝트: freeformz/shh
// Returns a slice of sorted strings from the environment or default split on ,
// So "foo,bar" returns ["bar","foo"]
func GetEnvWithDefaultStrings(env string, def string) []string {
	env = GetEnvWithDefault(env, def)
	if env == "" {
		return make([]string, 0)
	}
	tmp := strings.Split(env, ",")
	if !sort.StringsAreSorted(tmp) {
		sort.Strings(tmp)
	}
	return tmp
}
예제 #19
0
// testSortReversed runs the given sort function on an input set that
// is in reverse sorted order.
func testSortReversed(t *testing.T, f func([]string), size int) {
	checkTestSize(t, size)
	input := make([]string, size)
	copy(input, uniqueWords)
	ri := ReverseStringArray(input)
	sort.Sort(ri)
	f(input)
	if !sort.StringsAreSorted(input) {
		t.Error("reversed dictwords input not sorted")
	}
}
예제 #20
0
파일: sort_test.go 프로젝트: tornyak/goalg
func TestStrings(t *testing.T) {
	data := strings

	for _, alg := range algorithms {
		sorting.Strings(data[:], alg)
		if !sort.StringsAreSorted(data[:]) {
			t.Errorf("%v\n", util.GetFuncName(alg))
			t.Errorf("sorted: %v\n", strings)
			t.Errorf("   got: %v\n", data)
		}
	}
}
예제 #21
0
func main() {
	letters := []string{"f", "g", "a", "c", "e", "z", "b"}
	result := sort.StringsAreSorted(letters)
	fmt.Println(result)

	sort.Strings(letters)
	fmt.Println(letters)

	result = sort.StringsAreSorted(letters)
	fmt.Println(result)

	fmt.Println("---")

	numbers := []int{10, 40, 20, 5}
	result = sort.IntsAreSorted(numbers)
	fmt.Println(result)

	sort.Ints(numbers)
	fmt.Println(numbers)

	result = sort.IntsAreSorted(numbers)
	fmt.Println(result)
}
예제 #22
0
파일: da.go 프로젝트: sekineh/trie-1
func (this *DoubleArray) Build(a_keywords []string) {
	list := a_keywords
	if len(list) == 0 {
		return
	}
	if !sort.StringsAreSorted(list) {
		sort.Strings(list)
	}
	branches := make([]int, len(a_keywords))
	for i, size := 0, len(a_keywords); i < size; i++ {
		branches[i] = i
	}
	this.append(0, 0, branches, a_keywords)
}
예제 #23
0
func TestNodeDistance(t *testing.T) {
	nodes := make([]*node, 10)
	for i := 0; i < len(nodes); i++ {
		id := make([]byte, 20)
		id[19] = byte(i)
		nodes[i] = &node{
			NodeID: NodeID(id),
		}
	}

	tree := &routingTree{}
	for _, r := range nodes {
		r.LastRxTime = time.Now()
		tree.Insert(r)
	}

	var tests = []struct {
		Query InfoHash
		Want  int
	}{
		{MustParseInfoHash("0400000000000000000000000000000000000000"), 8},
		{MustParseInfoHash("0700000000000000000000000000000000000000"), 8},
	}

	for _, tst := range tests {
		distances := make([]string, 0, len(tests))
		neighbours := tree.Lookup(tst.Query)
		if len(neighbours) != tst.Want {
			t.Fatal()
		}

		for _, n := range neighbours {
			dist := hashDistance(tst.Query, InfoHash(n.NodeID))
			var b []string
			for _, c := range dist {
				if c != 0 {
					b = append(b, fmt.Sprintf("%08b", c))
				} else {
					b = append(b, "00000000")
				}
			}
			dist = strings.Join(b, ".")
			distances = append(distances, dist)
		}

		if !sort.StringsAreSorted(distances) {
			t.Fatal()
		}
	}
}
예제 #24
0
func TestMessageFromQuery(t *testing.T) {
	assert.True(t, sort.StringsAreSorted(protocolFields))

	for _, testCase := range messageFromQueryCases {
		message, err := MessageFromQuery(testCase.query)
		if err == nil {
			assert.Equal(t, message, testCase.expected)
		} else {
			if !assert.Equal(t, err, testCase.err) {
				fmt.Println(testCase.query)
			}
		}
	}
}
예제 #25
0
func TestNewFlake(t *testing.T) {
	f := New(1)

	var ids []string

	for i := 0; i < 4; i++ {
		id := f.NextID()

		ids = append(ids, id.String())
	}

	if !sort.StringsAreSorted(ids) {
		t.Errorf("IDs are not sorted!")
	}
}
예제 #26
0
파일: main.go 프로젝트: sim4life/go_poc
func main() {

	// Sort methods are specific to the builtin type;
	// here's an example for strings. Note that sorting is
	// in-place, so it changes the given slice and doesn't
	// return a new one.
	strs := []string{"can", "abs", "bus", "calli"}
	sort.Sort(sort.Reverse(sort.StringSlice(strs)))
	fmt.Println("Strings:", strs)
	fmt.Println("StringsAreSorted: ", sort.StringsAreSorted(strs))
	pos := sort.SearchStrings(strs, "bus") //doesn't work
	fmt.Printf("pos of \"bus\" in descending sorting is: %d\n", pos)
	pos = sort.SearchStrings(strs, "truck") //doesn't work
	fmt.Printf("pos of \"truck\" in descending sorting is: %d\n", pos)
	sort.Strings(strs)
	fmt.Println("Strings:", strs)
	fmt.Println("StringsAreSorted: ", sort.StringsAreSorted(strs))
	pos = sort.SearchStrings(strs, "bus")
	fmt.Printf("pos of \"bus\" in ascending sorting is: %d\n", pos)
	pos = sort.SearchStrings(strs, "truck")
	fmt.Printf("pos of \"truck\" in ascending sorting is: %d\n", pos)
	pos = sort.SearchStrings(strs, "call")
	fmt.Printf("pos of \"call\" in ascending sorting is: %d\n", pos)

	// An example of sorting `int`s.
	ints := []int{7, 2, 4}
	x := 4
	sort.Ints(ints)
	fmt.Println("Ints:   ", ints)
	pos = sort.SearchInts(ints, x)
	fmt.Printf("pos of %d in slice is: %d\n", x, pos)
	// We can also use `sort` to check if a slice is
	// already in sorted order.
	s := sort.IntsAreSorted(ints)
	fmt.Println("Sorted: ", s)
}
예제 #27
0
파일: dep.go 프로젝트: spenczar/godep
func uniq(a []string) []string {
	var s string
	var i int
	if !sort.StringsAreSorted(a) {
		sort.Strings(a)
	}
	for _, t := range a {
		if t != s {
			a[i] = t
			i++
			s = t
		}
	}
	return a[:i]
}
예제 #28
0
파일: dict.go 프로젝트: runeaune/mnemonic
func (d *Dictionary) LoadFromFile(path string) error {
	file, err := os.Open(path)
	if err != nil {
		return err
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		d.dict = append(d.dict, scanner.Text())
	}
	if !sort.StringsAreSorted(d.dict) {
		return fmt.Errorf("Words in file are not sorted.")
	}
	return scanner.Err()
}
예제 #29
0
// Creates an acyclic finite-state automaton from a sorted list of words and
// returns the root node. Words can contain any unicode chararcters. An error
// will be returned if the list of words is not lexicographically sorted.
func Create(words []string) (automaton *Node, err error) {
	reg := newRegistery()
	idGen := new(nodeIdGen)
	automaton = newNode(idGen)

	if !sort.StringsAreSorted(words) {
		err = errors.New("the words are not sorted")
		return
	}

	for _, word := range words {
		insertWord(word, automaton, reg, idGen)
	}

	replaceOrRegister(automaton, reg)
	return
}
예제 #30
0
func main() {
	// Simple sort
	nums := []int{6, 2, 7, 3, 10, 22, 9}
	sort.Ints(nums)
	Println("Sorted:", sort.IntsAreSorted(nums))
	Println(nums)

	strs := []string{"hello", "world", "and", "johnny"}
	sort.Strings(strs)
	Println("Sorted:", sort.StringsAreSorted(strs))
	Println(strs)

	// Custom function sort
	newNums := []int{6, 2, 7, 3, 10, 22, 9}
	sort.Sort(ReverseSort(newNums))
	Println(newNums)
}