David Lee
David Lee

Reputation: 601

How to return the indexes that tell the position of largest to smallest integers of an array in Ruby

Suppose I have an array of unique integers that contains 9 elements.

array = [3,5,7,9,2,4,8,1,6] 

How do I return an array of indexs that tell me the position of the original array of integers from largest to smallest?

index_of_largest_to_smallest = [3,6,2,8,1,5,0,4,7]

So this would tell me the largest number is at position 3, and the second largest is at position 6 etc.

I tried array.sort, but that sorts the array from largest to smallest. I also tried array.each_with_index but couldn't get it to return another array.

Upvotes: 3

Views: 86

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110675

array.each_index.sort_by { |i| -array[i] }
  #=> [3, 6, 2, 8, 1, 5, 0, 4, 7]

See the form of Array#each_index and Enumerable#sort_by. Note that Array#each_index returns an enumerator when, as here, no block is given.

Upvotes: 5

Stefan
Stefan

Reputation: 114158

Via each_with_index, sort, map, last and reverse:

[3,5,7,9,2,4,8,1,6].each_with_index   #=> [[3, 0], [5, 1], [7, 2], [9, 3], [2, 4], [4, 5], [8, 6], [1, 7], [6, 8]]
                   .sort              #=> [[1, 7], [2, 4], [3, 0], [4, 5], [5, 1], [6, 8], [7, 2], [8, 6], [9, 3]]
                   .map(&:last)       #=> [7, 4, 0, 5, 1, 8, 2, 6, 3]
                   .reverse           #=> [3, 6, 2, 8, 1, 5, 0, 4, 7]

Upvotes: 9

Related Questions