2016-11-10 20:01:22 -05:00
package utilities
import "errors"
2016-11-25 20:21:01 -05:00
/ *
The Pair and PairList have been taken from google groups forum ,
https : //groups.google.com/forum/#!topic/golang-nuts/FT7cjmcL7gw
* /
2016-11-10 20:01:22 -05:00
2016-12-22 23:17:01 -05:00
// Utility struct that helps in sorting a map[string]float64 by value.
2016-11-10 20:01:22 -05:00
type Pair struct {
2016-11-25 17:42:08 -05:00
Key string
Value float64
2016-11-10 20:01:22 -05:00
}
// A slice of pairs that implements the sort.Interface to sort by value.
type PairList [ ] Pair
// Swap pairs in the PairList
func ( plist PairList ) Swap ( i , j int ) {
2016-11-25 17:42:08 -05:00
plist [ i ] , plist [ j ] = plist [ j ] , plist [ i ]
2016-11-10 20:01:22 -05:00
}
// function to return the length of the pairlist.
func ( plist PairList ) Len ( ) int {
2016-11-25 17:42:08 -05:00
return len ( plist )
2016-11-10 20:01:22 -05:00
}
// function to compare two elements in pairlist.
func ( plist PairList ) Less ( i , j int ) bool {
2016-11-25 17:42:08 -05:00
return plist [ i ] . Value < plist [ j ] . Value
2016-11-10 20:01:22 -05:00
}
// convert a PairList to a map[string]float64
func OrderedKeys ( plist PairList ) ( [ ] string , error ) {
2016-11-25 17:42:08 -05:00
// Validation
if plist == nil {
return nil , errors . New ( "Invalid argument: plist" )
}
2016-11-28 17:18:33 -05:00
orderedKeys := make ( [ ] string , len ( plist ) )
2016-11-25 17:42:08 -05:00
for _ , pair := range plist {
2016-11-28 17:18:33 -05:00
orderedKeys = append ( orderedKeys , pair . Key )
2016-11-25 17:42:08 -05:00
}
2016-11-28 17:18:33 -05:00
return orderedKeys , nil
2016-11-10 20:01:22 -05:00
}
// determine the max value
func Max ( a , b float64 ) float64 {
2016-11-25 17:42:08 -05:00
if a > b {
return a
} else {
return b
}
2016-11-10 20:01:22 -05:00
}