Header Ad

HackerRank Ruby - Strings - Indexing problem solution

In this HackerRank Ruby - Strings - Indexing problem solution In this challenge, your task is to code a serial_average method which is described below:

It takes a fixed-width string in the format: SSS-XX.XX-YY.YY. SSS is a three-digit serial number, XX.XX and YY.YY are two-digit numbers including up to two decimal digits.

It returns a string containing the answer in format SSS-ZZ.ZZ where SSS is the serial number of that input string, and ZZ.ZZ is the average of XX.XX and YY.YY.

All numbers are rounded off to two decimal places.

For example:

> serial_average('002-10.00-20.00')

"002-15.00"

You can use string interpolation to insert Ruby code within a string.

For example:

> tmp = 123

> "Hello #{tmp}"

Hello 123

HackerRank Ruby - Strings - Indexing problem solution


Problem solution.

# Your code here
def serial_average(n)
    serial = n[0,3]
    first_num = n[4,5].to_f.round(2)
    sec_num = n[10,5].to_f.round(2)
    average = ((first_num + sec_num) / 2).round(2)
    
    return "#{serial}-#{average}"
end


Second solution.

# Your code here
def serial_average(s)
    serial = s[0, 3]
    x = s[4, 5].to_f
    y = s[10, 5].to_f
    z = (x + y) / 2
    "#{serial}-#{'%.2f' % z}"
end


Third solution.

def serial_average(s)
    sss = s[0..2]
    x_s = s[4..8].to_f
    y_s = s[10..14].to_f

    avg = ((x_s + y_s) / 2).round(2)
    return "#{sss}-#{avg}"
end


Post a Comment

0 Comments