From 04d6d4b63159aed89c16dad159721dd0e2f8383c Mon Sep 17 00:00:00 2001 From: Pradyumna Kaushik Date: Thu, 10 Nov 2016 20:01:22 -0500 Subject: [PATCH] Utility data structures and functions. --- utilities/utils.go | 54 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 utilities/utils.go diff --git a/utilities/utils.go b/utilities/utils.go new file mode 100644 index 0000000..d6406d6 --- /dev/null +++ b/utilities/utils.go @@ -0,0 +1,54 @@ +package utilities + +import "errors" + +/* +The Pair and PairList have been taken from google groups forum, +https://groups.google.com/forum/#!topic/golang-nuts/FT7cjmcL7gw +*/ + +// Utility struct that helps in sorting the available power by value. +type Pair struct { + Key string + Value float64 +} + +// 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) { + plist[i], plist[j] = plist[j], plist[i] +} + +// function to return the length of the pairlist. +func (plist PairList) Len() int { + return len(plist) +} + +// function to compare two elements in pairlist. +func (plist PairList) Less(i, j int) bool { + return plist[i].Value < plist[j].Value +} + +// convert a PairList to a map[string]float64 +func OrderedKeys(plist PairList) ([]string, error) { + // Validation + if plist == nil { + return nil, errors.New("Invalid argument: plist") + } + ordered_keys := make([]string, len(plist)) + for _, pair := range plist { + ordered_keys = append(ordered_keys, pair.Key) + } + return ordered_keys, nil +} + +// determine the max value +func Max(a, b float64) float64 { + if a > b { + return a + } else { + return b + } +}