Created
January 7, 2018 21:44
-
-
Save thesunwave/ca55866acd616d4acfe61eec90b7e4ca to your computer and use it in GitHub Desktop.
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
def sort(str) | |
arr = str.split(" ") | |
words = arr.map.with_index do |e, idx| | |
next if e =~ /-?\d+/ | |
[idx, e] | |
end.compact | |
nums = arr.map.with_index do |e, idx| | |
next unless e =~ /-?[0-9]/ | |
[idx, e] | |
end.compact | |
sorted_words = words.sort_by { |x| x.last } | |
sorted_nums = nums.sort_by { |x| x.last } | |
w = words.map.with_index do |w, idx| | |
[w[0], sorted_words[idx][1]] | |
end | |
n = nums.map.with_index do |n, idx| | |
[n[0], sorted_nums[idx][1]] | |
end | |
result = (w + n).sort_by { |x| x.first }.map { |x| x.last }.join(' ') | |
puts result | |
end | |
sort('car truck 8 4 bus 6 1') | |
sort('8 4 6 1 -2 9 5') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment