了解直方图

时间:2018-03-23 10:04:27

标签: ruby-on-rails ruby ruby-on-rails-3

好的,我发现了这个直方图的代码,我试图理解它是如何工作的,说实话,如果有更简单的方法来编写代码来做同样的事情这里但是时间较短。

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

1 个答案:

答案 0 :(得分:1)

试试这个。我拿了给定的代码并用函数重新编写它,我认为它是更具描述性的变量名;这使得它在LoC方面实际上更长,但应该帮助你了解结构。可以做很多事情来改进它,但我试图完全保留功能。

def count_entries_in_bin(array, bin_min, bin_max, chart)
  (array.count {|entry| entry >= bin_min and entry <= bin_max}).to_s.rjust((chart))
end

def generate_random_ordered_data
  array = []
  200.times do
    array.push(rand(1..100)).sort!
  end
  array
end

def print_histogram_header
  puts "  Range     #Found      Chart"
  puts " -------     ------    ------------------------------"
  puts
end

def start_new_row(array, bin_min, bin_max)
  print "\n"
  print "#{bin_min.to_s.center(RANGE_FIELD_MIN_WIDTH)} "
  print "- #{bin_max.to_s.rjust(FOUND_FIELD_MIN_WIDTH)}      "
  print "|#{count_entries_in_bin(array, bin_min, bin_max, CHART_FIELD_MIN_WIDTH)}|     *"
end

RANGE_FIELD_MIN_WIDTH = 1
FOUND_FIELD_MIN_WIDTH = 3
CHART_FIELD_MIN_WIDTH = 2
bin_min = 1
bin_max = 10

array = generate_random_ordered_data
print_histogram_header
print " 1 -  10      |#{count_entries_in_bin(array, bin_min, bin_max, CHART_FIELD_MIN_WIDTH)}|     "
array.each do |entry|
  if entry > bin_max
    bin_min += 10
    bin_max += 10
    start_new_row(array, bin_min, bin_max)
  else
    print "*"
  end
end