LoginSignup
0
0

More than 5 years have passed since last update.

array の中に要素として含まれているかの判定

Last updated at Posted at 2018-08-02

こんにちは。
Golang で array の中に要素として含まれているかの判定を行ってみました。array はソートされている必要があります。下記例ではint32 の array ですが、他の変数型の場合でも可能です(大小判定が可能ならば)。

import (
    "sort"
)

func contains(arr []int32, e int32) bool {
    i := sort.Search(len(arr), func(i int) bool { return e <= arr[i] })
    return i < len(arr) && e == arr[i]
}

sort.Slice(arr, func(i, j int) bool { return arr[i] < arr[j] })
if contains(arr, e) {
    fmt.Printf(...)
}
0
0
0

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
0
0