ary.each_index.sort_by{|i| ary[i]}
# => [4, 0, 1, 3, 5, 2]
Get indices for sorted permutation of an array in Ruby?
-
04-06-2022 - |
Pergunta
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).
Solução
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow