本文整理汇总了Golang中sort.Reverse函数的典型用法代码示例。如果您正苦于以下问题:Golang Reverse函数的具体用法?Golang Reverse怎么用?Golang Reverse使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Reverse函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: main
func main() {
fmt.Println("\nQuestion 1 results using my own type methods:")
studyGroup := people{"Zuno", "Derren", "Jahn", "Albert", "Jenny", "Rachel"}
sort.Sort(sort.Reverse(studyGroup)) // Using reverse interface
fmt.Println(studyGroup)
sort.Sort(studyGroup)
fmt.Println(studyGroup)
/*
(2)
s := []string{"Zeno", "John", "Al", "Jenny"}
*/
fmt.Println("\nQuestion 2 using StringSlice.")
s := []string{"Zeno", "John", "Al", "Jenny"}
// sort.Sort(sort.StringSlice(s))
sort.Strings(s) // Shorthand for above.
fmt.Println("Sorted:", s)
sort.Sort(sort.Reverse(sort.StringSlice(s)))
fmt.Println("Reversed sort:", s)
/*
(3)
n := []int{7, 4, 8, 2, 9, 19, 12, 32, 3}
*/
fmt.Println("\nQuestion 3, int slice sorting:")
n := []int{7, 4, 8, 2, 9, 19, 12, 32, 3}
sort.Ints(n) // Shorthand for using IntSlice - look at doc.
fmt.Println("Sorted using Ints, shorthand for IntSlice:", n)
sort.Sort(sort.Reverse(sort.IntSlice(n)))
fmt.Println("Reversed Ints:", n)
}
示例2: main
func main() {
nums := []int{120, 33, 44, 1, 23, 90, 87, 13, 57, 43, 42}
//标准库qsort 正序(实际上是qsort结合heapsort,insertsort)
sort.Ints(nums)
fmt.Println(nums)
//反序qsort
sort.Sort(sort.Reverse(sort.IntSlice(nums)))
fmt.Println(nums)
//正序bubble
bubbleSort(sort.IntSlice(nums))
fmt.Println(nums)
//反序bubble
bubbleSort(sort.Reverse(sort.IntSlice(nums)))
fmt.Println(nums)
//正序insert
insertSort(sort.IntSlice(nums))
fmt.Println(nums)
//反序inert
insertSort(sort.Reverse(sort.IntSlice(nums)))
fmt.Println(nums)
//正序select
selectSort(sort.IntSlice(nums))
fmt.Println(nums)
//反序select
selectSort(sort.Reverse(sort.IntSlice(nums)))
fmt.Println(nums)
}
示例3: Euler041
func Euler041() int {
//process 7 digit pandigitals
p7d := make([]int, 0, 5040) //7!
for v := range utils.Perm(utils.Numerals[1:8]) {
n, _ := strconv.Atoi(v)
p7d = append(p7d, n)
}
sort.Sort(sort.Reverse(sort.IntSlice(p7d)))
for i := 0; i < 5040; i++ {
if utils.IsPrime(p7d[i]) {
return p7d[i]
}
}
//process 4 digit pandigitals
p4d := make([]int, 0, 24) //4!
for v := range utils.Perm(utils.Numerals[1:5]) {
n, _ := strconv.Atoi(v)
p4d = append(p4d, n)
}
sort.Sort(sort.Reverse(sort.IntSlice(p4d)))
for i := 0; i < 5040; i++ {
if utils.IsPrime(p4d[i]) {
return p4d[i]
}
}
return -1
}
示例4: allocateCandidates
// allocateCandidates creates a candidate list of all stores that can used for
// allocating a new replica ordered from the best to the worst. Only stores
// that meet the criteria are included in the list.
func allocateCandidates(
sl StoreList,
constraints config.Constraints,
existing []roachpb.ReplicaDescriptor,
existingNodeLocalities map[roachpb.NodeID]roachpb.Locality,
deterministic bool,
) candidateList {
var candidates candidateList
for _, s := range sl.stores {
if !preexistingReplicaCheck(s.Node.NodeID, existing) {
continue
}
constraintsOk, preferredMatched := constraintCheck(s, constraints)
if !constraintsOk {
continue
}
if !maxCapacityCheck(s) {
continue
}
constraintScore := diversityScore(s, existingNodeLocalities) + float64(preferredMatched)
candidates = append(candidates, candidate{
store: s,
valid: true,
constraint: constraintScore,
capacity: capacityScore(s),
})
}
if deterministic {
sort.Sort(sort.Reverse(byScoreAndID(candidates)))
} else {
sort.Sort(sort.Reverse(byScore(candidates)))
}
return candidates
}
示例5: sortList
// sortList sorts lists (like substitutions) from a string:string map.
func sortList(dict map[string]string) []string {
output := []string{}
// Track by number of words.
track := map[int][]string{}
// Loop through each item.
for item, _ := range dict {
cnt := wordCount(item, true)
if _, ok := track[cnt]; !ok {
track[cnt] = []string{}
}
track[cnt] = append(track[cnt], item)
}
// Sort them by word count, descending.
sortedCounts := []int{}
for cnt, _ := range track {
sortedCounts = append(sortedCounts, cnt)
}
sort.Sort(sort.Reverse(sort.IntSlice(sortedCounts)))
for _, cnt := range sortedCounts {
// Sort the strings of this word-count by their lengths.
sortedLengths := track[cnt]
sort.Sort(sort.Reverse(byLength(sortedLengths)))
for _, item := range sortedLengths {
output = append(output, item)
}
}
return output
}
示例6: formCards
func formCards(cards []*Card, c Config) []*Card {
var ranks []Rank
if c.aceIsLow {
// sort cards staring w/ king
sort.Sort(sort.Reverse(byAceLow(cards)))
// sort ranks starting w/ king
ranks = allRanks()
sort.Sort(sort.Reverse(byAceLowRank(ranks)))
} else {
// sort cards staring w/ ace
sort.Sort(sort.Reverse(byAceHigh(cards)))
// sort ranks starting w/ ace
ranks = allRanks()
sort.Sort(sort.Reverse(byAceHighRank(ranks)))
}
// form cards starting w/ most paired
formed := []*Card{}
for i := 4; i > 0; i-- {
for _, r := range ranks {
rCards := cardsForRank(cards, r)
if len(rCards) == i {
formed = append(formed, rCards...)
}
}
}
dif := 5 - len(formed)
for i := 0; i < dif; i++ {
s := fmt.Sprintf("?%d", i+1)
formed = append(formed, &Card{rank: Rank(s), suit: Suit(s)})
}
// check for low straight
return formLowStraight(formed)
}
示例7: main
func main() {
// sort people as type
studyGroup := people{"Zeno", "John", "Al", "Jenny"}
fmt.Println(studyGroup)
sort.Sort(studyGroup)
fmt.Println(studyGroup)
sort.Sort(sort.Reverse(studyGroup))
fmt.Println(studyGroup)
// sort s as string slice
s := []string{"Zeno", "John", "Al", "Jenny"}
fmt.Println(s)
sort.StringSlice(s).Sort()
fmt.Println(s)
sort.Sort(sort.Reverse(sort.StringSlice(s)))
fmt.Println(s)
// sort n as int slice
n := []int{7, 4, 8, 2, 9, 19, 12, 32, 3}
fmt.Println(n)
sort.IntSlice(n).Sort()
fmt.Println(n)
sort.Sort(sort.Reverse(sort.IntSlice(n)))
fmt.Println(n)
}
示例8: main
func main() {
studyGroup := people{"Zeno", "Ian", "John", "Al", "Jenny"}
fmt.Println("1: = sorting slice of strings of type people by name:")
fmt.Println("\to:", studyGroup)
sort.Strings(studyGroup)
fmt.Println("\t\t [Strings method]:", studyGroup)
sort.Sort(sort.StringSlice(studyGroup))
fmt.Println("\t\t [StringSlice interface conversion]", studyGroup)
sort.Sort(sort.Reverse(sort.StringSlice(studyGroup)))
fmt.Println("\t\t [Reverse]", studyGroup)
fmt.Println("2: = by literal slice of strings")
s := []string{"Zeno", "John", "Al", "Jenny", "Ben"}
fmt.Println("\to:", s)
sort.Strings(s)
fmt.Println("\t\t [Strings method]:", s)
sort.Sort(sort.StringSlice(s))
fmt.Println("\t\t [StringSlice interface conversion]", s)
sort.Sort(sort.Reverse(sort.StringSlice(s)))
fmt.Println("\t\t [Reverse]", s)
fmt.Println("3: = slice of ints")
n := []int{7, 4, 8, 2, 9, 19, 12, 32, 3}
fmt.Println("\to:", n)
sort.Ints(n)
fmt.Println("\t\t [Ints method]", n)
sort.Sort(sort.IntSlice(n))
fmt.Println("\t\t [IntSlice interface conversion]", n)
sort.Sort(sort.Reverse(sort.IntSlice(n)))
fmt.Println("\t\t [Reverse]", n)
}
示例9: applySort
// Add sorting method to "Listing"
// it will apply what's in ".Sort" and ".Order"
func (l Listing) applySort() {
// Check '.Order' to know how to sort
if l.Order == "desc" {
switch l.Sort {
case "name":
sort.Sort(sort.Reverse(byName(l)))
case "size":
sort.Sort(sort.Reverse(bySize(l)))
case "time":
sort.Sort(sort.Reverse(byTime(l)))
default:
// If not one of the above, do nothing
return
}
} else { // If we had more Orderings we could add them here
switch l.Sort {
case "name":
sort.Sort(byName(l))
case "size":
sort.Sort(bySize(l))
case "time":
sort.Sort(byTime(l))
default:
// If not one of the above, do nothing
return
}
}
}
示例10: main
func main() {
s := []*Organ{
{"spleen", 162},
{"pacreas", 131},
{"liver", 1494},
{"heart", 290},
{"brain", 1340},
}
for _, o := range s {
fmt.Println(o)
}
fmt.Println("before sort", s)
// sort
sort.Sort(ByWeight{s})
fmt.Println("Organs by weight", s)
sort.Sort(ByName{s})
fmt.Println("Organs by name", s)
// reverse
fmt.Println("before reverse", s)
sort.Sort(sort.Reverse(ByWeight{s}))
fmt.Println("Organs by weight", s)
sort.Sort(sort.Reverse(ByName{s}))
fmt.Println("Organs by name", s)
}
示例11: main
func main() {
intList := []int{2, 4, 3, 5, 7, 6, 9, 8, 1, 0}
float8List := []float64{4.2, 5.9, 12.3, 10.0, 50.4, 99.9, 31.4, 27.81828, 3.14}
stringList := []string{"a", "c", "b", "d", "f", "i", "z", "x", "w", "y"}
fmt.Println("------------正序---------------")
sort.Ints(intList)
sort.Float64s(float8List)
sort.Strings(stringList)
fmt.Printf("%v\n%v\n%v\n", intList, float8List, stringList)
fmt.Println("------------倒序---------------")
sort.Sort(sort.Reverse(sort.IntSlice(intList)))
sort.Sort(sort.Reverse(sort.Float64Slice(float8List)))
sort.Sort(sort.Reverse(sort.StringSlice(stringList)))
fmt.Printf("%v\n%v\n%v\n", intList, float8List, stringList)
fmt.Println("-------------结构体(特定字段)排序-----------")
people := []Person{
{"zhang san", 12},
{"li si", 30},
{"wang wu", 52},
{"zhao liu", 26},
}
fmt.Println(people)
sort.Sort(PersonWrapper{people, func(p, q *Person) bool {
return q.Age < p.Age //Age 递减排序
}})
fmt.Println(people)
sort.Sort(PersonWrapper{people, func(p, q *Person) bool {
return p.Name < q.Name //Name 递增排序
}})
fmt.Println(people)
}
示例12: ByWinnings
func (s PlayerStandings) ByWinnings(oldTieBreak bool) {
if oldTieBreak {
sort.Sort(sort.Reverse(ByWinningsOld{s}))
} else {
sort.Sort(sort.Reverse(ByWinnings{s}))
}
}
示例13: sortByWords
/*
sortByWords sorts a set of triggers by word count and overall length.
This is a helper function for sorting the `atomic`, `option`, `alpha`, `number`
and `wild` attributes of the sortTrack and adding them to the running sort
buffer in that specific order. Since attribute lookup by reflection is expensive
in Go, this function is given the relevant sort buffer directly, and the current
running sort buffer to add the results to.
The `triggers` parameter is a map between word counts and the triggers that
fit that number of words.
*/
func sortByWords(running []sortedTriggerEntry, triggers map[int][]sortedTriggerEntry) []sortedTriggerEntry {
// Sort the triggers by their word counts from greatest to smallest.
var sortedWords []int
for wc := range triggers {
sortedWords = append(sortedWords, wc)
}
sort.Sort(sort.Reverse(sort.IntSlice(sortedWords)))
for _, wc := range sortedWords {
// Triggers with equal word lengths should be sorted by overall trigger length.
var sortedPatterns []string
patternMap := map[string][]sortedTriggerEntry{}
for _, trig := range triggers[wc] {
sortedPatterns = append(sortedPatterns, trig.trigger)
if _, ok := patternMap[trig.trigger]; !ok {
patternMap[trig.trigger] = []sortedTriggerEntry{}
}
patternMap[trig.trigger] = append(patternMap[trig.trigger], trig)
}
sort.Sort(sort.Reverse(byLength(sortedPatterns)))
// Add the triggers to the running triggers bucket.
for _, pattern := range sortedPatterns {
running = append(running, patternMap[pattern]...)
}
}
return running
}
示例14: PrioritizeTags
// PrioritizeTags orders a set of image tags with a few conventions:
//
// 1. the "latest" tag, if present, should be first
// 2. any tags that represent a semantic major version ("5", "v5") should be next, in descending order
// 3. any tags that represent a semantic minor version ("5.1", "v5.1") should be next, in descending order
// 4. any tags that represent a full semantic version ("5.1.3-other", "v5.1.3-other") should be next, in descending order
// 5. any remaining tags should be sorted in lexicographic order
//
// The method updates the tags in place.
func PrioritizeTags(tags []string) {
remaining := tags
finalTags := make([]string, 0, len(tags))
for i, tag := range tags {
if tag == DefaultImageTag {
tags[0], tags[i] = tags[i], tags[0]
finalTags = append(finalTags, tags[0])
remaining = tags[1:]
break
}
}
exact := make(map[string]string)
var major, minor, micro semver.Versions
other := make([]string, 0, len(remaining))
for _, tag := range remaining {
short := strings.TrimLeft(tag, "v")
v, err := semver.Parse(short)
switch {
case err == nil:
exact[v.String()] = tag
micro = append(micro, v)
continue
case reMajorSemantic.MatchString(short):
if v, err = semver.Parse(short + ".0.0"); err == nil {
exact[v.String()] = tag
major = append(major, v)
continue
}
case reMinorSemantic.MatchString(short):
if v, err = semver.Parse(short + ".0"); err == nil {
exact[v.String()] = tag
minor = append(minor, v)
continue
}
}
other = append(other, tag)
}
sort.Sort(sort.Reverse(major))
sort.Sort(sort.Reverse(minor))
sort.Sort(sort.Reverse(micro))
sort.Sort(sort.StringSlice(other))
for _, v := range major {
finalTags = append(finalTags, exact[v.String()])
}
for _, v := range minor {
finalTags = append(finalTags, exact[v.String()])
}
for _, v := range micro {
finalTags = append(finalTags, exact[v.String()])
}
for _, v := range other {
finalTags = append(finalTags, v)
}
copy(tags, finalTags)
}
示例15: viterbi
func viterbi(obs []rune, states []byte) (float64, []byte) {
path := make(map[byte][]byte)
V := make([]map[byte]float64, len(obs))
V[0] = make(map[byte]float64)
for _, y := range states {
if val, ok := ProbEmit[y][obs[0]]; ok {
V[0][y] = val + ProbStart[y]
} else {
V[0][y] = MIN_FLOAT + ProbStart[y]
}
path[y] = []byte{y}
}
for t := 1; t < len(obs); t++ {
newPath := make(map[byte][]byte)
V[t] = make(map[byte]float64)
for _, y := range states {
vs0 := make(Viterbis, 0)
var em_p float64
if val, ok := ProbEmit[y][obs[t]]; ok {
em_p = val
} else {
em_p = MIN_FLOAT
}
for _, y0 := range PrevStatus[y] {
var transP float64
if tp, ok := ProbTrans[y0][y]; ok {
transP = tp
} else {
transP = MIN_FLOAT
}
prob0 := V[t-1][y0] + transP + em_p
vs0 = append(vs0, &Viterbi{prob: prob0, state: y0})
}
sort.Sort(sort.Reverse(vs0))
V[t][y] = vs0[0].prob
pp := make([]byte, len(path[vs0[0].state]))
copy(pp, path[vs0[0].state])
newPath[y] = append(pp, y)
}
path = newPath
}
vs := make(Viterbis, 0)
for _, y := range []byte{'E', 'S'} {
vs = append(vs, &Viterbi{V[len(obs)-1][y], y})
}
sort.Sort(sort.Reverse(vs))
v := vs[0]
return v.prob, path[v.state]
}