Skip to content

Instantly share code, notes, and snippets.

@iwan
Last active August 29, 2015 13:57
Show Gist options
  • Select an option

  • Save iwan/9888087 to your computer and use it in GitHub Desktop.

Select an option

Save iwan/9888087 to your computer and use it in GitHub Desktop.
Sorting two arrays
# Given two 'linked' array, you want to sort one and reorder the second to preserve the same sequence of the first:
a = [3,2,7,5,1,9,3]
b = [:a, :b, :c, :d, :e, :f, :g]
def a.sort_with(arr)
raise "the two array must have the same size" if size!=arr.size
h = self.collect.with_index{|e,i| [e, arr[i]]}.sort{|x,y| y.first<=>x.first}
[h.map{|e| e.first}, h.map{|e| e.last}]
end
puts a.sort_with(b).inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment