HACKERRANK: CLEAN CODE: GRADING STUDENTS

By: Saurav

2017-12-28 04:25:00 UTC

HackerLand University has the following grading policy:

Every student receives a in the inclusive range from to .
Any less than is a failing grade.
Sam is a professor at the university and likes to round each student's according to these rules:

If the difference between the and the next multiple of is less than , round up to the next multiple of .
If the value of is less than , no rounding occurs as the result will still be a failing grade.
For example, will be rounded to but will not be rounded because the rounding would result in a number that is less than .

Given the initial value of for each of Sam's students, write code to automate the rounding process. For each , round it according to the rules above and print the result on a new line.

Input Format

The first line contains a single integer denoting (the number of students).
Each line i of the n subsequent lines contains a single integer grade_i , denoting student 's grade.

Constraints:

1<= n <= 60
0<= grade_i <= 100

Output Format

For each grade_i of the n grades, print the rounded grade on a new line.

HackerRank

Sample Input 0

4
73
67
38
33
Sample Output 0

75
67
40
33

Great that tests are already given. That's one thing hate/like about hackerrank depending upon if I am in mood or writing tests first.

Following the 10 steps to solve any Interview question, we need to ask for constraints, edge cases, space and time complexity needed. This is one of those problems where thinking of edge case is very important.

This is a simple comparison problem, kinda maths problem where we need to write good comparison logic:

H = (5..100).step(5)

def get_multiple_of_five_greater_than_number(n)
    H.each do |i|
        return i if i >= n
    end 
end

def get_rounded_number(n)
    return n if n > 100
    return n if n < 38
    return 40 if n == 38
    return 40 if n == 39    
    (get_multiple_of_five_greater_than_number(n) - n).abs < 3 ? get_multiple_of_five_greater_than_number(n) : n    
end

n = gets.to_i
input_array = Array.new
(0..n-1).each do |i|
    input_array << gets.to_i
end

input_array.each do |n|
    puts get_rounded_number(n)
end

Looks pretty good to me.


Let me know what you think!
Twitter: sprakash24oct
Linkedin

Owned & Maintained by Saurav Prakash

If you like what you see, you can help me cover server costs or buy me a cup of coffee though donation :)