Sample Input : “car truck 8 4 bus 6 1”
Sample Output : “bus car 1 4 truck 6 8”
If the nth element in the string is an integer it must remain an integer,
and if it is a word it must remain a word
Is there a more elegant and efficient way of doing this? Below is my ruby code. I am looking for code which is more efficient(need not be in ruby).
puts "Enter Input:"
inp = gets
inp_ary=inp.split(" ")
a=inp_ary.group_by{|i| i=~ /\d/}
sort_words = a[nil].sort
sort_integer = a[0].sort
index_words=[]
index_integer=[]
inp_ary.each_with_index do |e,i|
if e =~ /\d/
index_integer << i
else
index_words << i
end
end
final = []
sorted = sort_words + sort_integer
index_integer.each_with_index do |e,i|
final[e] = sort_integer[i]
end
index_words.each_with_index do |e,i|
final[e] = sort_words[i]
end
puts "Sorted Output: "
puts final.join(" ")
1 Answer