RoboCode RoboCode - 5 months ago 13
Ruby Question

Find the index by current sort order of an array in ruby

If there is an array

array A = ["a","b","c","d"] #Index is [0,1,2,3]


And it's sorted to.

array A = ["d","c","b","a"]


I need an array that returns me the updated index based on the sorted order

[3,2,1,0]


I'm trying to find a solution to this ruby

UPDATE to the question

If a is sorted to


array A = ["d","b","c","a"] #not a pure reverse


Then the returned index array should be

[3,1,2,0]

Answer

You need to create a mapping table that preserves the original order, then use that order to un-map the re-ordered version:

orig = %w[ a b c d ]
orig_order = orig.each_with_index.to_h

revised = %w[ d c b a ]

revised.map { |e| orig_order[e] }
# => [3, 2, 1, 0]

So long as your elements are unique this will be able to track any shift in order.

Comments