Forum: Ruby Would this be possible?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
9666efc2a9d84c6c5d2d84bc8b496e1c?d=identicon&s=25 Craig Schweitzer (Guest)
on 2006-03-28 02:21
Would this work to find the mean average and the number of elements
greater than the average?



# Calculating Avg and # of elements greater than Avg. in Ruby

sum = 0.0
n = 0
count = 0

while figure = STDIN.gets.to_f
    sum += figure
    n += 1
end

average = sum / n
puts "Average = #{average}"

while figure = STDIN.gets.to_f
     if figure > average
          count +=1
     end
end

puts â??Number of elements greater than Avg = #{count}â?
81d609425e306219d54d793a0ad98bce?d=identicon&s=25 Matthew Moss (Guest)
on 2006-03-28 02:38
(Received via mailing list)
I'm not sure how that would work....  you're re-reading the input stream
twice.

Anyway, here's my version.  I could compact it more, but I won't try
confusing you too much all at once.  =)


figures = STDIN.read.split("\n").map { |x| x.to_f }

sum = figures.inject { |s, x| s + x }
average = sum / figures.size
high = figures.select { |x| x > average }

puts "Average: #{average}"
puts "Count greater than average: #{high.size}"
2e34f386b20cb7c11c4204d699babd78?d=identicon&s=25 Chris Alfeld (Guest)
on 2006-03-28 02:43
(Received via mailing list)
There are a few problems.

* Your input loop will never exit.  On EOF STDIN.gets will return nil
and then you call nil.to_f which is 0.0, which is a true value.

* Your output needs new lines.

Consider

----
input = []
while a = STDIN.gets
  input << a.to_f
end

average = input.inject(0) {|m,x| m = m+x} / input.size
count = input.count {|x| x > average}

print "Average = #{average}\n"
print "Number of elements greater than Avg = #{count}\n"
----
2e34f386b20cb7c11c4204d699babd78?d=identicon&s=25 Chris Alfeld (Guest)
on 2006-03-28 02:46
(Received via mailing list)
Or even better:

----
input = STDIN.readlines.collect {|x| x.to_f}

average = input.inject(0) {|m,x| m = m+x} / input.size
count = input.count {|x| x > average}

print "Average = #{average}\n"
print "Number of elements greater than Avg = #{count}\n"
----
This topic is locked and can not be replied to.