0
\$\begingroup\$

I'm looking for a more elegant solutions of this task.

Task: Given a string, print its even-indexed and odd-indexed characters as space-separated strings on a single line.

Input Format: The first line contains an integer (the number of test cases). Each line of the subsequent lines contain a string.

puts "Input a number of test cases"
t = gets.to_i
t.times do
  puts "Input a string please"  
  s = gets.strip
  z = s.split(//)
  b = z.each_with_index.sort_by { |i, x| [x.even? ? 0 : 1, x] }
  b.map { |i, x| print i if x.even? }
  print " "
  b.map { |i, x| print i if x.odd? }
  puts
end
\$\endgroup\$
3
\$\begingroup\$

It's a good idea to become familiar with all the methods on Array and Enumerable. It just so happens that Enumerable has a method called partition that has a purpose of dividing an array into .two parts (e.g. even and odd). It'll help tidy up your code.

So let's use partition on the array of chars and partition based on index.

parts = s.chars.partition.with_index{|_,i| i.even?}

Note since we are only using the index, the actual character is unimportant so I used _ instead of a variable name in the partition block. Now you have two arrays of characters--let's join each array so that you have a single array with two strings:

strings = parts.map(&:join)

If you don't know about &:join it is a shortcut for {|a| a.join} (using Symbol#to_proc if you want to read up on it).

Then, finally print it. Note that in your code, you intermingle printing with manipulation. This is best avoided if you can; print only once you have things in final form.

print strings.join(' ')

The above could all be put together in one line if you'd rather:

print s.chars.partition.with_index{|_,i| i.even?}.map(&:join).join(' ')
\$\endgroup\$
  • 1
    \$\begingroup\$ thanks for the answer, I was sure there is a magiс one-liner for this thing :). \$\endgroup\$ – edvard_munch May 29 '17 at 13:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.