Skip to content

Instantly share code, notes, and snippets.

@willf willf/argmax.go Secret
Created Jun 15, 2011

Embed
What would you like to do?
ArgMax on ints
type Increasing interface {
Less(i, j int) bool
Len() int
}
func ArgMax(data Increasing) (index int) {
for i := 0; i < data.Len(); i++ {
if i==0 || data.Less(index,i) {
index = i
}
}
return
}
type IntArray []int
func (p IntArray) Len() int { return len(p) }
func (p IntArray) Less(i, j int) bool { return p[i] < p[j] }
func ArgMaxInt(arr []int) (index int, max int) {
for i,n := range arr {
if i==0 || n > max {
index = i
max = n
}
}
return
}
func main() {
array := []int{1,2,3,4,5,6,7,6,5,4,11113,2,1}
a := IntArray(array[0:])
i,max := ArgMaxInt(array)
println(i)
println(max)
println(ArgMaxGeneric(a))
}
@willf

This comment has been minimized.

Copy link
Owner Author

commented Jun 15, 2011

Example, at least, of how to write ArgMax in Go -- One generic way, and one specific to Ints (which could be described as Uints, etc)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.