Skip to content

Instantly share code, notes, and snippets.

@willf

willf/argmax.go Secret

Created June 15, 2011 05:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save willf/8856a9ce3b18c7550db7 to your computer and use it in GitHub Desktop.
Save willf/8856a9ce3b18c7550db7 to your computer and use it in GitHub Desktop.
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
Copy link
Author

willf 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