6
1

More than 3 years have passed since last update.

Goでスライス内の最大値・最小値を抽出する関数

Posted at

はじめに

Goでコードを書いているとスライス内の最大値、もしくは最小値を算出する処理を
何度か利用したので忘れないためにもメモ

スライス内の最大値を取得

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]
}

サンプルコード

以下コードを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]
}

参考

6
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
1