Created
September 8, 2021 11:02
-
-
Save martinusso/c16602a0647fe0ed92ea210c6fd95bd1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A data structure to hold key/value pairs | |
type Pair struct { | |
Key string | |
Value float64 | |
} | |
// A slice of pairs that implements sort.Interface to sort by values | |
type PairList []Pair | |
func (p PairList) Len() int { return len(p) } | |
func (p PairList) Swap(i, j int) { p[i], p[j] = p[j], p[i] } | |
func (p PairList) Less(i, j int) bool { return p[i].Value < p[j].Value } | |
func sortMapByValues(m map[string]float64) PairList { | |
p := make(PairList, len(m)) | |
i := 0 | |
for k, v := range m { | |
p[i] = Pair{k, v} | |
i++ | |
} | |
/* | |
fmt.Printf("Pre-sorted: ") | |
for _, k := range p { | |
fmt.Printf("%s %v\n", k.Key, k.Value) | |
} | |
fmt.Println("") | |
*/ | |
sort.Sort(p) | |
/* | |
fmt.Printf("Post-sorted: ") | |
for _, k := range p { | |
fmt.Printf("%s %v\n", k.Key, k.Value) | |
} | |
ret := map[string]float64{} | |
for _, k := range p { | |
ret[k.Key] = k.Value | |
} | |
return ret | |
*/ | |
return p | |
} | |
func reverseMapByValues(m map[string]float64) PairList { | |
p := make(PairList, len(m)) | |
i := 0 | |
for k, v := range m { | |
p[i] = Pair{k, v} | |
i++ | |
} | |
/* | |
fmt.Printf("Pre-sorted: ") | |
for _, k := range p { | |
fmt.Printf("%s %v\n", k.Key, k.Value) | |
} | |
fmt.Println("") | |
*/ | |
sort.Sort(sort.Reverse(p)) | |
/* | |
fmt.Printf("Post-sorted: ") | |
for _, k := range p { | |
fmt.Printf("%s %v\n", k.Key, k.Value) | |
} | |
ret := map[string]float64{} | |
for _, k := range p { | |
ret[k.Key] = k.Value | |
} | |
return ret | |
*/ | |
return p | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment