vendredi 23 mars 2018

Understanding histogram

OK I found this code of a histogram, I'm trying to understand how it works to be honest, an if there's an easier way to write out the code to do the same thing as its doing here but in a shorter way.

def histogram(array, start, stop, chart)
  (array.count {|array| array >= start and array <= stop}).to_s.rjust((chart))
end

array, stop, range, found, chart, start = [], 10, 1, 3, 2, 1

200.times do
  array.push(rand(1..100)).sort!
end

puts "  Range     #Found      Chart" "\n" " -------     ------    ------------------------------"
puts
print " 1 -  10      |#{histogram(array, start, stop, chart)}|     "
array.each do |counts|
  if counts > stop
    print "\n"
    start += 10
    stop += 10
    print "#{start.to_s.center(range)} "
    print "- #{stop.to_s.rjust(found)}      "
    print "|#{histogram(array, start, stop, chart)}|     *"
  else
    print "*"
  end
end

Aucun commentaire:

Enregistrer un commentaire