Sha256: 9c448583d67b4a58f7cd7df394d92d4ee0b2419d6882a182ad6c7498f38b6398

Contents?: true

Size: 1.22 KB

Versions: 33

Compression:

Stored size: 1.22 KB

Contents

module EverydayCliUtils
  class Histogram
    def self.setup(collection, height, width)
      mi     = collection.min
      ma     = collection.max
      diff   = ma - mi
      step   = diff.to_f / (width.to_f - 1)
      counts = Array.new(width, 0)
      collection.each { |v| counts[((v - mi).to_f / step.to_f).floor] += 1 }
      max_y = counts.max
      lines = Array.new(height) { ' ' * width }
      return counts, lines, max_y, mi, step
    end

    def self.add_graph(counts, height, lines, max_y, width)
      (0...width).each { |i|
        h = ((counts[i].to_f / max_y.to_f) * height.to_f).round
        ((height - h)...height).each { |j|
          lines[j][i] = '#'
        }
        if h == 0 && counts[i] > 0
          lines[height - 1][i] = '_'
        end
      }
    end

    def self.add_averages(height, ks, lines, mi, step, width)
      lines[height] = ' ' * width
      ks.each { |v| lines[height][((v - mi) / step).to_i] = '|' }
    end

    def self.histogram(collection, ks = nil, width = 100, height = 50)
      counts, lines, max_y, mi, step = setup(collection, height, width)
      add_graph(counts, height, lines, max_y, width)
      add_averages(height, ks, lines, mi, step, width) unless ks.nil?
      lines
    end
  end
end

Version data entries

33 entries across 33 versions & 1 rubygems

Version Path
everyday-cli-utils-1.8.7.2 lib/everyday-cli-utils/safe/histogram.rb
everyday-cli-utils-1.8.7.1 lib/everyday-cli-utils/safe/histogram.rb
everyday-cli-utils-1.8.7 lib/everyday-cli-utils/safe/histogram.rb
everyday-cli-utils-1.8.6 lib/everyday-cli-utils/safe/histogram.rb
everyday-cli-utils-1.8.5 lib/everyday-cli-utils/safe/histogram.rb
everyday-cli-utils-1.8.4 lib/everyday-cli-utils/safe/histogram.rb
everyday-cli-utils-1.8.3 lib/everyday-cli-utils/safe/histogram.rb
everyday-cli-utils-1.8.2 lib/everyday-cli-utils/safe/histogram.rb
everyday-cli-utils-1.8.1 lib/everyday-cli-utils/safe/histogram.rb
everyday-cli-utils-1.8.0 lib/everyday-cli-utils/safe/histogram.rb
everyday-cli-utils-1.7.4 lib/everyday-cli-utils/safe/histogram.rb
everyday-cli-utils-1.7.3 lib/everyday-cli-utils/safe/histogram.rb
everyday-cli-utils-1.7.2 lib/everyday-cli-utils/safe/histogram.rb
everyday-cli-utils-1.7.1 lib/everyday-cli-utils/safe/histogram.rb
everyday-cli-utils-1.7.0 lib/everyday-cli-utils/safe/histogram.rb
everyday-cli-utils-1.6.0 lib/everyday-cli-utils/safe/histogram.rb
everyday-cli-utils-1.5.2 lib/everyday-cli-utils/safe/histogram.rb
everyday-cli-utils-1.5.1 lib/everyday-cli-utils/safe/histogram.rb
everyday-cli-utils-1.5.0 lib/everyday-cli-utils/safe/histogram.rb
everyday-cli-utils-1.4.0 lib/everyday-cli-utils/safe/histogram.rb