LoginSignup
0
0

More than 3 years have passed since last update.

NimでmaxIndex, minIndexをしっかり取りたい

Posted at

nimのsequtilsには1.2から maxIndex, minIndex という配列の最大値、最小値のindexを取得でき便利なメソッドがある。しかし、これは最大値、最小値をとる最初のindexを返すので同値のものが複数含まれる場合はそれが取得できない問題がある。

import sequtils

const data = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]

echo data.maxIndex # 3
echo data.minIndex # 0

mapやfilterなどをつかってとろうと思ったがmapにもindexを取得する術がない。

解決

ないので自前で用意するしかない。
pairs iteratorを使えば愚直にindexをとれるので以下のような実装でできた。
これで最大値をとる最後のindexなどが取得できる。

const data = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]

proc findIndexes[T](items: openArray[T], value: T): seq[int] =
  var indexes = newSeq[int]()
  for index, item in items.pairs:
    if item == value:
      indexes.add(index)
  return indexes

proc maxIndexes[T](items: openArray[T]): seq[int] =
  return items.findIndexes(items.max)

proc minIndexes[T](items: openArray[T]): seq[int] =
  return items.findIndexes(items.min)

echo data.maxIndexes # @[3, 7, 11]
echo data.minIndexes # @[0, 4, 8]

mapやfilterでもindexがほしいので、標準で実装してほしい...
つくられるつもりがなければ、自前でライブラリをつくるかもしれない。

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