Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get indices for sorted permutation of an array in Ruby?

Let's say I have an Array ary = [0.0, 1.0, 5.0, 1.0, -2.0, 3.5], and I want as output another array of the same size containing ary's indices in sorted-by-value-order. In other words, the output should be [4,0,1,3,5,2]. Is there an efficient way to do this with Enumerable or Array?

The most trivial solution I can imagine is as follows:

class Array
  def sorted_indices
    self.map.with_index{ |v,i| [v,i] }.sort{ |a,b| a[0] <=> b[0] }.map { |v| v[1] }
  end
end

but I feel like there has to be something simpler already built in.

It's important to note that the values in the array are not unique. No index should appear in the result array more than once (in other words, [4,0,1,1,5,2] is not correct).

like image 290
Translunar Avatar asked Jul 24 '13 17:07

Translunar


1 Answers

ary.each_index.sort_by{|i| ary[i]}
# => [4, 0, 1, 3, 5, 2]
like image 57
sawa Avatar answered Sep 23 '22 16:09

sawa