0

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].

3
  • 2
    I (and I expect others) cannot infer your question from an example. Please edit to state your question in words, then, if necessary, give one or more examples, each with the desired result. Also, please double-check your values. Commented Jun 14, 2017 at 6:02
  • This seems clumsy and not sure if it's robust ((a & b).sort_by {|e| a.index(e)}) + (b - (a & b)).sort #=> [1, 2, 13, 4, 10, 23, 44, 55] Commented Jun 14, 2017 at 6:10
  • Please provide more information on your logic for sorting. It's not clear as to why expected output has to be [1, 2, 13, 4, 10, 23, 44, 55]? Commented Jun 14, 2017 at 6:25

1 Answer 1

4

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] }
Sign up to request clarification or add additional context in comments.

1 Comment

I feel that complexity can be improved here. Perhaps by hashifying the order array, as attempted in the question. But this, as it is, certainly should work, yes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.