Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an array of numbers based on a given order

Tags:

ruby

I have two arrays. The first array contains the sort order. The second array contains an arbitrary number of elements.

I have the property that all elements (value-wise) from the second array are guaranteed to be in the first array, and I am only working with numbers.

A = [1,3,4,4,4,5,2,1,1,1,3,3]
Order = [3,1,2,4,5]

When I sort A, I would like the elements to appear in the order specified by Order:

[3, 3, 3, 1, 1, 1, 1, 2, 4, 4, 4, 5]

Note that duplicates are fair game. The elements in A should not be altered, only re-ordered. How can I do this?

like image 872
MxLDevs Avatar asked May 13 '12 18:05

MxLDevs


1 Answers

>> source = [1,3,4,4,4,5,2,1,1,1,3,3]
=> [1, 3, 4, 4, 4, 5, 2, 1, 1, 1, 3, 3]
>> target = [3,1,2,4,5]
=> [3, 1, 2, 4, 5]
>> source.sort_by { |i| target.index(i) }
=> [3, 3, 3, 1, 1, 1, 1, 2, 4, 4, 4, 5]
like image 74
Gareth Avatar answered Sep 23 '22 02:09

Gareth