I've been looking around to learn about histograms, and haven't had any
luck... can someone tell me how a histogram would work for something
like this:
Name, Age
Bob, 2
Jim, 2
Eric, 4
Rob, 5
Depending on how you get that data, FasterCSV might be a good option, but I'll just create a nested array for illustration.
ages = [ ['Bob', 2], ['Jim',2], ['Eric',4], ['Rob',5] ]
How would I use a histogram to get a result like this:
Age | Names
2 | Bob, Jim
4 | Eric
5 | Rob
Thanks in advance!!!
So the answer you want is: (note that I'm using a Hash since the keys will be unique anyway)
histogram = { 2 => ['Bob','Jim'], 4 => ['Eric'], 5 => ['Rob'] }
So you could just use Enumerable#group_by (provided by the ActiveSupport gem from Rails; yes, you can use it by itself). Of course, it's also a simple matter to group them yourself:
histogram = Hash.new { |h,k| h[k] = } # hash that defaults values to empty Arrays
ages.each {|name,age| histogram[age] << name }
If you need to produce that exact output:
puts "Age | Names"
histogram.sort_by {|age,names| age}.each do |age,names|
puts "%-3d | %s"%[age, names*', ']
end
Age | Names
2 | Bob, Jim
4 | Eric
5 | Rob
And I expect that you have a lot of thumbing through the Pickaxe to understand all that
-Rob
Rob Biedenharn http://agileconsultingllc.com
Rob@AgileConsultingLLC.com
···
On Jun 5, 2008, at 6:01 PM, Justin To wrote: