简体   繁体   English

参照另一个数组对数组进行排序

[英]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 . 现在我要排序的数组b参照阵列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. 但是我得到了KeyError: key not found: 44错误。 Can anyone help me find a solution? 谁能帮我找到解决方案?

Expected output is [1, 2, 13, 4, 10, 23, 44, 55] . 预期输出为[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 : 因此,这将根据出现的顺序(在a与未在a的实际值进行比较:

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

To keep O(nlogn), you could: 要保留O(nlogn),您可以:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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