Juliaの整列順列関数とその応用 sortperm
コード
sortpermは与えられた配列をソートされた状態にするためのインデックスの配列を返す1。言葉だけ見ると難しそうだけど、例を見るとすぐに理解できる。
julia> foo = ['다', '나', '라', '가']
4-element Vector{Char}:
 '다': Unicode U+B2E4 (category Lo: Letter, other)
 '나': Unicode U+B098 (category Lo: Letter, other)
 '라': Unicode U+B77C (category Lo: Letter, other)
 '가': Unicode U+AC00 (category Lo: Letter, other)
julia> sortperm(foo)
4-element Vector{Int64}:
 4
 2
 1
 3
julia> foo[sortperm(foo)]
4-element Vector{Char}:
 '가': Unicode U+AC00 (category Lo: Letter, other)
 '나': Unicode U+B098 (category Lo: Letter, other)
 '다': Unicode U+B2E4 (category Lo: Letter, other)
 '라': Unicode U+B77C (category Lo: Letter, other)
テクニック
組み込み関数ではないが、sortpermでよく使われるテクニックを紹介する。
ranking
ranking(x) = sortperm(sortperm(x, rev = true))
配列のランキングを返す。ランキング関数は統計関連のパッケージであるStatBase.jlにもある2。しかし、sortpermだけでも簡単に実装できるので、ランキングだけが必要な場合はパッケージをロードせずにこのように使うこともある。
julia> a = randn(5)
5-element Vector{Float64}:
  0.7795283609374186
  0.6230493124556412
  1.7323736283590032
 -2.0790567409341945
 -0.05984808360056012
julia> ranking(a)
5-element Vector{Int64}:
 2
 3
 1
 5
 4
argnth
argnth(n, A) = sortperm(A, rev = true)[n]
n番目に大きい要素のインデックスを返す。いざsortpermなしで書こうとすると、実装が面倒になる。
julia> b = randn(5)
5-element Vector{Float64}:
 -0.45523175238444824
  0.2671034422090365
 -1.0703159524443844
 -0.4218688982647255
 -0.27806227968448743
julia> argnth(3, b)
4
環境
- OS: Windows
 - julia: v1.10.0
 
