Amazon Affiliate

Monday 11 April 2016

Print the fraction of the elements of an array according to positive, negative and zero in ruby.

# Given an array of integers, calculate which fraction of its elements are positive, which fraction of its elements are negative, and and which fraction of its elements are zeroes, respectively. Print the decimal value of each fraction on a new line.

# Note: This challenge introduces precision problems. The test cases are scaled to six decimal places.

# Input Format :

# The first line contains an integer, N, denoting the size of the array.
# The second line contains N space-separated integers describing an array of numbers
# (a0,a1,a2,…,an−1)(a0,a1,a2,…,an−1).

# Output Format :

# You must print the following 3 lines:

#     A decimal representing of the fraction of positive numbers in the array.
#     A decimal representing of the fraction of negative numbers in the array.
#     A decimal representing of the fraction of zeroes in the array.


puts "Enter the size of array :"
n = gets.strip.to_i
puts "Enter the elements :"
arr = gets.strip
arr = arr.split(' ').map(&:to_i)
positive_count = 0
negative_count = 0
zero_count = 0
for i in (0..n-1)
    if arr[i] > 0
        positive_count += 1
    elsif arr[i] < 0
        negative_count += 1
    else
        zero_count += 1
    end
end       
puts (positive_count/n.to_f).round(6)
puts (negative_count/n.to_f).round(6)
puts (zero_count/n.to_f).round(6)
               

No comments:

Post a Comment