LoginSignup
3
2

More than 5 years have passed since last update.

【Go】Goのsort.SearchInts()はPHPのin_array()とは全然違った!

Last updated at Posted at 2015-08-21

最近Goを始めたばかりのPHPerなのですが、PHPのin_array()のようなものをGoでも使いたいな、、と。
調べると、「sort」というパッケージを発見しました。

ちょうどその時やりたかったことが、sort.SearchInts()で実現できるのでは!?
と思ったのですが、全然違った、というお話です。

Go公式サイトの日本語翻訳サイトで調べてみた

上記のSearchInts()の説明では、

SearchIntsは、ソート済みintのスライスからxを検索し、Searchで規定されているインデックスを返します。

とあります。

返り値がそもそも真偽値ではないのでin_array()と違うのは当然ですが、
それでも、検索結果がなければ、ないことがわかるような値が返ってくるのではと漠然と思っていました。

package main

import (
    "fmt"
    "sort"
)

func main() {
    a := []int{1,9,3,7,5}
    // まずソートする
    sort.Ints(a)
    fmt.Printf("%v\n", a) // [1 3 5 7 9]

    // インデックス3が返ってくるはず...
    b := sort.SearchInts(a, 7)
    fmt.Printf("%v\n", b) // 3

    // スライスの中にないことが分かるような値が返ってきてほしい...
    c := sort.SearchInts(a, 4)
    fmt.Printf("%v\n", c) // 2
}

!?

c := sort.SearchInts(a, 4)
fmt.Printf("%v\n", c) // 2

スライスの中に値がなくても数値が返ってきました。。

本家のドキュメントで確認しよう

そこで、改めて本家のドキュメントを見てみると、

func SearchStrings(a []string, x string) int

SearchStrings searches for x in a sorted slice of strings and returns the index as specified by Search. The return value is the index to insert x if x is not present (it could be len(a)). The slice must be sorted in ascending order.

おや...

The return value is the index to insert x if x is not present (it could be len(a)).

英語あんまりわからないけど、´・ω・
「xがない場合は、xが挿入される箇所のインデックスが返される」みたいなことが書いてあります。(あってるかな?)

なので、

c := sort.SearchInts(a, 4)
fmt.Printf("%v\n", c) // 2

の例だと
「4はスライスの中に値はないけど、対象のスライスのソート順だとインデックス2の位置に入りますよ。」
という情報が得られるようです。

間違っていたらご指摘いただけるとありがたいです・ω・

結局

in_array()は下記を参考に自前で用意します。。
http://qiita.com/taro_sakura/items/32552e2d953cd73f578b
https://gist.github.com/kn9ts/3b9833758283993264b0

3
2
4

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
3
2