2

Possible Duplicate:
Ruby: Sorting 2 arrays using values from one of them

I have an array that looks like this:

a = [[0,1], [1,2], [2,3]]

and an array b like this:

b = [5, 3, 4]

The elements in b correspond to the elements in a on the same index. I want to sort band at the same time the elements in a to change order in the same way as b.

So for the above example I would get:

a = [[1, 2], [2, 3], [0, 1]] and b = [3, 4, 5]

How can I do that?

1

3 Answers 3

3
a = [[0,1], [1,2], [2,3]]
b = [5, 3, 4]
a, b = b.zip(a).sort.transpose
p b #=> [[1, 2], [2, 3], [0, 1]]

To see how this works, just look at the result of p b.zip(a); then p b.zip(a).transpose.

4
  • I would prefer sort_by(&:first) Oct 2, 2012 at 15:17
  • @VictorMoroz Or sort_by(&:join) to sort by all digits.
    – Robert K
    Oct 2, 2012 at 15:24
  • @RobertK: But what happens when you have things like [11, 1] and [1, 11]? Oct 2, 2012 at 15:38
  • Ruby can sort by array, why bother using first ,last or even join? Just use [[11,1],[1,11]].sort, you will get [[1, 11], [11, 1]]
    – SwiftMango
    Oct 2, 2012 at 15:43
1

Here's a quick benchmark to show the outputs and execution times:

require 'benchmark'
require 'pp'

a = [[0,1], [1,2], [2,3]]
b = [5, 3, 4]

pp a.sort_by.with_index{|_,i| b[i]}

a,b = b.zip(a).sort.transpose 
pp b

a = [[0,1], [1,2], [2,3]]
b = [5, 3, 4]
n = 1_000_000

puts "Using #{n} iterations:"
Benchmark.bm(7) do |bench|
  bench.report('sort_by') { n.times { a.sort_by.with_index{|_,i| b[i]} } }
  bench.report('zip')     { n.times { b.zip(a).sort.transpose } }
end

Here's the output:

[[1, 2], [2, 3], [0, 1]]
[[1, 2], [2, 3], [0, 1]]
Using 1000000 iterations:
              user     system      total        real
sort_by   2.370000   0.000000   2.370000 (  2.371345)
zip       2.730000   0.000000   2.730000 (  2.730663)
2
  • Thanks for the data man. And this is the performance for only array of 3 items.
    – SwiftMango
    Oct 2, 2012 at 17:05
  • Yes, only three, done a million times. It'd be all relative with variations on the iterations or the array sizes. Oct 2, 2012 at 18:17
0

Even though @steenslag gives a good solution, I would still not recommend using zip for its low performance, especially if the arrays are large because it generates an intermediate array.

The following code is more straight forward:

a = [[0,1], [1,2], [2,3]]
b = [5, 3, 4]
p a.sort_by.with_index{|_,i| b[i]}

Output:

[[1, 2], [2, 3], [0, 1]]
2
  • Even I give a good solution? :)
    – steenslag
    Oct 2, 2012 at 15:52
  • @steenslag Even Ruby is not very good at performance, I would still try to minimize the performance issue. Your solution will iterate a and b once each, generate an intermediate array with size a+b, and then generates an intermediate hash for sorting. Mine iterates a once, then generates a sorting hash :)
    – SwiftMango
    Oct 2, 2012 at 16:02

Not the answer you're looking for? Browse other questions tagged or ask your own question.