简体   繁体   中英

Sort the array with reference to another array

I have two different arrays. Let's say:

a = [1, 2, 13, 4, 10, 11, 43]
b = [44, 23, 1, 4, 10, 2, 55, 13]

Now I have to sort the array b by referring to the array a . I tried the following solution:

lookup = {}
a.each_with_index do |item, index|
  lookup[item] = index
end

b.sort_by do |item|
  lookup.fetch(item)
end

But I'm getting the KeyError: key not found: 44 error. Can anyone help me find a solution?

Expected output is [1, 2, 13, 4, 10, 23, 44, 55] .

Comparing arrays checks the first value, if it's equal goes to the second value and so on. Hence this will compare by the order of occurrence in a and then by the actual value for the ones not in a :

b.sort_by { |e| [a.index(e) || a.size, e] }

To keep O(nlogn), you could:

ai = a.each_with_index.to_h
b.sort_by { |e| [ai[e] || a.size, e] }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM