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

五迷三道 提交于 2020-01-17 06:57:05

问题


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]

回答1:


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.




回答2:


Here is one way to do this:

original_array = ["a","b","c","d"]
jumbled_array = original_array.shuffle

jumbled_array.map {|i| original_array.index(i)}
#=> [1, 3, 0, 2] 

Note:

  1. In this sample, output will change for every run as we are using shuffle to demonstrate the solution.
  2. The solution will work only as long as array has no duplicate values.

If you do wish to solution to work with arrays with duplicate values, then, one possibility is to look at object_id of array members while figuring out the index.

jumbled_array.map {|i| original_array.map(&:object_id).index(i.object_id)}

This solution will work as long as jumbled_array contains element from original_array and no elements were recreated using dup or something that results in change in object_id values




回答3:


You can use the map and index methods.

arr = ["a","b","c","d"]

sort_arr = ["d","c","b","a"]

sort_arr.map{|s| arr.index(s)}
# => [3, 2, 1, 0]


来源:https://stackoverflow.com/questions/37995867/find-the-index-by-current-sort-order-of-an-array-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!