Sort an array of numbers based on a given order
ruby
Solution
>> 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]
Problem
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?