Created
July 13, 2015 04:32
-
-
Save yswallow/4db38d4b827becba522a to your computer and use it in GitHub Desktop.
Rubyで可逆ソート
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
| class Array | |
| protected | |
| attr_accessor :matrix | |
| public | |
| def sort_with_matrix | |
| item_with_index = self.map.with_index { |item,i| [item,i] } | |
| item_with_index.sort_by! { |item,i| item } | |
| new_array = [] | |
| matrix = [] | |
| item_with_index.each do |item,i| | |
| new_array << item | |
| matrix << i | |
| end | |
| new_array.matrix = matrix | |
| return new_array | |
| end | |
| def sort_with_matrix! | |
| new_array = self.sort_with_matrix | |
| self.replace(new_array) | |
| @matrix = new_array.matrix | |
| return self | |
| end | |
| def unsort | |
| new_array = [] | |
| @matrix.each_with_index do |j,i| | |
| new_array[j] = self[i] | |
| end | |
| @matrix = [] | |
| return new_array | |
| end | |
| def unsort! | |
| self.replace(self.unsort) | |
| @matrix = [] | |
| self | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment