When writing code in Go, the process of calculating the maximum value or the minimum value in the slice I used it several times, so make a note so that I don't forget it.
func maxInt(a []int) int {
sort.Sort(sort.IntSlice(a))
return a[len(a)-1]
}
func minInt(a []int) int {
sort.Sort(sort.IntSlice(a))
return a[0]
}
Copy and execute the following code with The Go Playground
package main
import "fmt"
import "sort"
func main() {
test := []int{7, 8 ,1, 4, 3, 21}
fmt.Println("max:", maxInt(test))
fmt.Println("min:", minInt(test))
}
func maxInt(slice []int) int {
sort.Sort(sort.IntSlice(slice))
return slice[len(slice)-1]
}
func minInt(slice []int) int {
sort.Sort(sort.IntSlice(slice))
return slice[0]
}
Recommended Posts