Added min and max

This commit is contained in:
btracey
2013-05-16 00:11:04 -07:00
parent a3e7ae41b6
commit 563cf6d5bd
2 changed files with 90 additions and 0 deletions

41
sliceops.go Normal file
View File

@@ -0,0 +1,41 @@
package sliceops
//import "math"
// Returns the minimum value in the slice and the index of
// the minimum value. If the input slice is empty, zero is returned
// as the minimum value and -1 is returned as the index.
// Use: val,ind := sliceops.Min(slice)
func Min(s []float64) (min float64, ind int) {
if len(s) == 0 {
return min, -1 // Ind is -1 to make clear it's not the zeroth index.
}
min = s[0]
ind = 0
for i, val := range s {
if val < min {
min = val
ind = i
}
}
return min, ind
}
// Returns the maximum value in the slice and the location of
// the maximum value. If the input slice is empty, zero is returned
// as the minimum value and -1 is returned as the index.
// Use: val,ind := sliceops.Max(slice)
func Max(s []float64) (max float64, ind int) {
if len(s) == 0 {
return max, -1 // Ind is -1 to make clear it's not the zeroth index.
}
max = s[0]
ind = 0
for i, val := range s {
if val > max {
max = val
ind = i
}
}
return max, ind
}

49
sliceops_test.go Normal file
View File

@@ -0,0 +1,49 @@
package sliceops
import (
"testing"
)
const (
SmallBenchmark = 10
MediumBenchmark = 1000
LargeBenchmark = 100000
)
func TestMin(t *testing.T) {
s := []float64{}
val, ind := Min(s)
if val != 0 {
t.Errorf("Val not returned as default when slice length is zero")
}
if ind != -1 {
t.Errorf("Ind not returned as -1 for empty slice")
}
s = []float64{3, 4, 1, 7, 5}
val, ind = Min(s)
if val != 1 {
t.Errorf("Wrong minimum returned")
}
if ind != 2 {
t.Errorf("Wrong index returned")
}
}
func TestMax(t *testing.T) {
s := []float64{}
val, ind := Max(s)
if val != 0 {
t.Errorf("Val not returned as default when slice length is zero")
}
if ind != -1 {
t.Errorf("Ind not returned as -1 for empty slice")
}
s = []float64{3, 4, 1, 7, 5}
val, ind = Max(s)
if val != 7 {
t.Errorf("Wrong minimum returned")
}
if ind != 3 {
t.Errorf("Wrong index returned")
}
}