Last active
August 29, 2015 13:57
-
-
Save iwan/9888087 to your computer and use it in GitHub Desktop.
Sorting two arrays
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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