Reputation: 79450
Say I have 2 arrays like this:
# base set
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# sub set
b = [5, 1, 8, 3]
What's the optimal way to sort b
to the same order as a
?
a.sort_like(b) #=> [1, 3, 5, 8]
What is this operation called?
Upvotes: 1
Views: 319
Reputation: 31776
If b is a subset of a, as you have defined, then the result is going to always be the sorted version of b. In which case, the you just want b.sort
(it won't mutate b, it will return a new array with the sorted contents of b).
Upvotes: -1
Reputation: 5413
This will do it, I'm not sure about the most efficient way.
def sort_like(other)
items = []
other.each do |find|
each do |item|
items.append item if item == find
end
end
items
end
Upvotes: 1