本文介绍了根据另一阵列的元素进行排序的阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组ID

  A1 = [1,2,3,4,5]
 

和我有对象的另一个数组与IDS以随机顺序

  A2 = [(obj_with_id_5),(obj_with_id_2),(obj_with_id_1),(obj_with_id_3),(obj_with_id_4)]
 

现在我需要A2按照A1 ID的顺序进行排序。所以A2现在应该变成:

  [(obj_with_id_1),(ID_2),(ID_3),(ID_4),(ID_5)]
 

A1可能是[3,2,5,4,1]或以任何顺序,但A2应该对应于a1中的ID的顺序。

我不喜欢这样的:

  a1.each_with_index办| ID,IDX |
  found_idx = a1.find_index {| C | c.id == ID}
  replace_elem = A2 [found_idx]
  A2 [found_idx] = A2 [IDX]
  A2 [IDX] = replace_elem
结束
 

不过,这仍然可能会遇到一个为O(n ^ 2)时间,如果为了A2的元素是完全扭转A1的。是否有人可以告诉我整理A2的最有效方法是什么?

解决方案

  hash_object = objects.each_with_object({})办| OBJ,散列|
  哈希[obj.object_id] = OBJ
结束

[1,2,3,4,5] .MAP {|首​​页| hash_object [指数]}
#=>对象的ID的顺序排列
 

我认为,运行时间将是为O(n)

I have an array of ids

a1 = [1, 2, 3, 4, 5]  

and I have another array of objects with ids in random order

a2 = [(obj_with_id_5), (obj_with_id_2), (obj_with_id_1), (obj_with_id_3), (obj_with_id_4)]  

Now I need to sort a2 according to the order of ids in a1. So a2 should now become:

[(obj_with_id_1), (id_2), (id_3), (id_4), (id_5)]  

a1 might be [3, 2, 5, 4, 1] or in any order but a2 should correspond to the order of ids in a1.

I do like this:

a1.each_with_index do |id, idx|
  found_idx = a1.find_index { |c| c.id == id }
  replace_elem = a2[found_idx]
  a2[found_idx] = a2[idx]
  a2[idx] = replace_elem
end  

But this still might run into an O(n^2) time if order of elements of a2 is exactly reverse of a1. Can someone please tell me the most efficient way of sorting a2?

解决方案
hash_object = objects.each_with_object({}) do |obj, hash| 
  hash[obj.object_id] = obj
end

[1, 2, 3, 4, 5].map { |index| hash_object[index] }
#=> array of objects in id's order

I believe that the run time will be O(n)

这篇关于根据另一阵列的元素进行排序的阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 05:56