Wednesday Mar 07, 2007
Wednesday Mar 07, 2007
#!/bin/env ruby -w
# Given an array, print it as a bar graph
# Use it at your own risk
class HorizBar
WIDTH = 72
HEIGHT = 16
def initialize(array)
@values = array
end
def draw
#Adjust X axis when there are more than WIDTH cols
if @values.length > WIDTH then
old_values = @values;
@values = []
0.upto(WIDTH - 1){ |i| @values << old_values[i*old_values.length/WIDTH]}
end
max = @values.max
# initialize display with blanks
display = Array.new(HEIGHT).collect { Array.new(WIDTH, ' ') }
@values.each_with_index do |e, i|
num= e*HEIGHT/max
(HEIGHT - 1).downto(HEIGHT - 1 - num){|j| display[j][i] = '|'}
end
display.each{|ar| ar.each{|e| putc e}; puts "\n"} #now print
end
end
# Sample usage 1
sample = [28829, 29095, 29301, 31827, 43478, 52937,62969]
HorizBar.new(sample).draw
# Another Sample usage
a = []
100.times { a << rand(100)}
HorizBar.new(a).draw
It produces output similar to
| | | | | | | | | | | | | | | | | || | | | | || | | || | | | || | | | | | || | | | || | | | | || || || | | | ||| | | | ||| || | | | || | || || | | || | ||| | | | ||| || | | | || | | || || | | | || || | ||| | | | ||| || | | | || | | || || | | | || || | ||| | | | | ||| || | | | || | | ||||| | | | || ||| | ||| | | ||| ||| || | | | || | || ||||| | | | || ||| | ||| | | ||||||||| || | || | || | || ||||| || || | | || ||| || ||| ||| ||||||||| || | || |||| | || ||||| || || | | || ||| || ||| ||| |||||||||| || || || | |||| | ||| ||||| |||||| || | || |||||| ||| ||| |||||||||| || || || |||||| | |||||| ||||| |||||| ||||||| |||||| ||| |||||||||||||| |||||||| |||||| | |||||| ||||| |||||||||||||||||||||||||||||||||||||||||||||||||||||||| |||||||| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Rudimentary, but quite useful if you want to look at some data quickly.