IDの配列があります
a1 = [1, 2, 3, 4, 5]
ランダムな順序でIDを持つオブジェクトの別の配列があります
a2 = [(obj_with_id_5), (obj_with_id_2), (obj_with_id_1), (obj_with_id_3), (obj_with_id_4)]
次に、a1のIDの順序に従ってa2を並べ替える必要があります。したがって、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 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
ただし、a2の要素の順序がa1とまったく逆の場合、これはO(n ^ 2)時間に達する可能性があります。誰かがa2をソートする最も効率的な方法を教えてもらえますか?