views:

60

answers:

2

Lets say I have an array : a=[[1,2,3],[4,5]] and I have another array : b=[[2.5,1.5,3.5],[1.5,2.5]]

I need to sort 'a' with respect to 'b'. i.e the output should be = [[3,1,2],[5,4]]

I tried but my code seemed to be very lengthy. It would be great if you could help me out.Thanks!

+3  A: 

This gives your sample output for your sample input, so hopefully it's what you want (it sorts the values of each subarray in the first array by the value at the same position in the corresponding subarray of the second array, descendingly):

class Array
  def sort_by_other_array(arr)
    zip(arr).sort_by {|x,y| y}.map {|x,y| x}
  end
end

a=[[1,2,3],[4,5]]
b=[[2.5,1.5,3.5],[1.5,2.5]]
a.zip(b).map {|x,y| x.sort_by_other_array(y).reverse}
#=> [[3, 1, 2], [5, 4]]
sepp2k
+1  A: 

Next time, it would be a great idea to post your code, and an explanation of the context can also be handy.

Here's a way to get your desired results

a.zip(b).map do |values, sort_values|
  sort_values.zip(values).sort.reverse_each.map{|sort, value| value}
end
Marc-André Lafortune