Skip to content

Instantly share code, notes, and snippets.

@reinh
Created March 11, 2009 18:03
Show Gist options
  • Save reinh/77610 to your computer and use it in GitHub Desktop.
Save reinh/77610 to your computer and use it in GitHub Desktop.
#!/bin/env ruby -wdK
# Given an array, print it as a bar graph
# Use FOR SPEED!!!
class VertiBar
WIDTH = 72
STEPS = WIDTH/6
def self.draw(sample)
new(sample).draw
end
def initialize(array)
@values = array
@height = array.size
@max = array.max
end
private :initialize
# initialize display with blanks
def graph
@values.map do |value|
line = value * WIDTH / @max
str = "%f" % value + ' ' + '#' * (line - 12)
color = @values.outlier?(value) ? :red : :none
str = CLI.colorize(str, color)
str
end
end
def markers
(1..STEPS).map{|i| i * @max.ceil / STEPS }.map{|i| i.to_s.rjust(6, '-')}.join
end
def draw
puts graph
puts markers
puts
printf "The mean is %f\n", @values.without_outliers.average
printf "The standard deviation is %f\n", @values.without_outliers.standard_deviation
end
end
module CLI
class << self
COLORS = {
:none => "\033[0m",
:red => "\033[31m",
:green_bg => "\033[42m",
:red_bg => "\033[41m",
:white_bg => "\033[47m"
}
def colorize(text, color)
"#{COLORS[color]}#{text}\033[0m"
end
end
end
module Enumerable
def sum
self.inject(0) { |acc, i| acc + i }
end
def average
self.sum / self.length.to_f
end
def outlier?(item)
item > self.max * 0.9 || item < self.max * 0.1
end
def without_outliers
reject{|item| self.outlier?(item) }
end
def sample_variance
avg = self.average
sum = self.inject(0) { |acc, i| acc + (i - avg) ** 2 }
(1 / self.length.to_f * sum)
end
def standard_deviation
Math.sqrt(self.sample_variance)
end
end
if __FILE__ == $PROGRAM_NAME
sample = [545.993804931641, 560.154914855957, 660.984992980957, 594.608068466187, 563.859939575195, 669.82889175415, 577.944040298462, 688.918828964233, 990.634918212891, 582.823038101196, 676.376104354858, 584.000825881958, 587.714910507202, 662.652969360352, 575.167179107666, 696.619987487793, 563.127040863037, 571.943044662476, 685.527801513672, 590.106010437012]
VertiBar.draw sample
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment