8
arr = [1,3,2,4]

arr.sort #=> [1,2,3,4]

配列が欲しい[0, 2, 1, 3](元のインデックスがarr.sort順番に)

Ruby 1.9.3でそれを行う簡単な方法はありますか?

ありがとうございました

4

6 に答える 6

20
xs = [1, 3, 2, 4]
original_indexes = xs.map.with_index.sort.map(&:last)
#=> [0, 2, 1, 3]
于 2013-01-21T20:07:51.403 に答える
1
arr=[1,3,2,4]
p arr.map{|e| arr.sort.index(e)}

毎回ソートを避けるために、より良いのは次のとおりです。

arr=[1,3,2,4]
arr_s = arr.sort
p arr.map{|e| arr_s.index(e)}

更新しました

arr=[1,3,2,4]
start_time = Time.now
(1..100000).each do |i|
    arr.map{|e| arr.sort.index(e)}
end
elapsed = Time.now - start_time
p elapsed

xs = [1, 3, 2, 4]
start_time = Time.now
(1..100000).each do |i|
    xs.map.with_index.sort.map(&:last)
end
elapsed = Time.now - start_time
p elapsed

そして結果を得ました:

0.281736
0.504314
于 2013-01-21T20:12:33.017 に答える
0

I tested on MRI Ruby 2.2.1p85 (on both Mac and CentOS), tokland's solution return a wrong result:

xs = [8,3,2,7,5]
xs.map.with_index.sort.map(&:last)
#=> [2, 1, 4, 3, 0] # wrong

Yevgeniy Anfilofyev solution works but does not support non-unique array:

arr = [8,3,2,7,5]
arr_s = arr.sort
arr.map{|e| arr_s.index(e)}
#=> [4, 1, 0, 3, 2] # correct

arr = [8,3,5,2,8,8,7,5]
arr_s = arr.sort
arr.map{|e| arr_s.index(e)}
#=> [5, 1, 2, 0, 5, 5, 4, 2]

I come up this:

arr = [8,3,5,2,8,8,7,5]
index_order = []
arr.uniq.sort.each do |a|
  index_order += arr.each_index.select{|i| arr[i] == a }
end
r = []
index_order.each_with_index do |a, i|
  r[a] = i
end
r
#=> [5, 1, 2, 0, 6, 7, 4, 3]
于 2015-08-04T04:44:21.190 に答える