Categories
Program Ruby Tutorial

HackerRank – 30 Days of Code – Day 6: Let’s Review – Ruby Program

Objective

Today we’re expanding our knowledge of Strings and combining it with what we’ve already learned about loops. Check out the Tutorial tab for learning materials and an instructional video!

Task

Given a string, S, of length N that is indexed from 0 to N-1, print its even-indexed and odd-indexed characters as 2 space-separated strings on a single line (see the Sample below for more detail).

Note: 0 is considered to be an even index.

Input Format

The first line contains an integer, T (the number of test cases).
Each line of the T subsequent lines contain a String, S.

Constraints

  • 1 <= T <= 10
  • 2 <= length of S <= 10000

Output Format

For each String Sj(where 0<=j<=T-1), print Sj’s even-indexed characters, followed by a space, followed by Sj’s odd-indexed characters.

Sample Input

2
Hacker
Rank

Sample Output

Hce akr
Rn ak
Explanation

Ruby Implementation

T = gets.to_i
S = Array.new
Output = Array.new

T.times do | array_index |
    S.push(gets.chomp)
end

T.times do | array_index |    
    temp_string = S[array_index]
    string_count = S[array_index].to_s.length
    odd = ""
    even = ""

    
    string_count.times do | string_index |
        if(string_index %2 == 0)
            even = even + temp_string[string_index]
        else
            odd = odd + temp_string[string_index]
        end
    end
    
    Output.push(even + " " + odd)
end

puts Output

 


Sourcehttps://www.hackerrank.com/challenges/30-review-loop/copy-from/30480794

Leave a Reply

Your email address will not be published. Required fields are marked *