On 03/18/2010 11:50 PM, Steve Wilhelm wrote:
> I have an array of records that contain timestamps at random intervals.
> The records are ordered by timestamp.
> 
> I would like to convert the array into an array of arrays; each subarray
> would contain "grouped records." Grouping would occur if the timestamp
> of the next element in the original array is within thirty seconds of
> the current element.
> 
> Example (second column is timestamp in seconds starting from zero).
> 
> A 0
> B 15
> C 35
> D 100
> E 205
> F 215
> G 300
> 
> would result in
> 
> [[A, B, C], [D], [E, F], [G]]
> 
> Any help on how to do this in the "Ruby Way" would be appreciated.

Assuming records are ordered already - otherwise you need a sort in between.

require 'pp'

dat = <<DDD.each_line.map {|l|r = l.split;r[1]=r[1].to_i;r}
A 0
B 15
C 35
D 100
E 205
F 215
G 300
DDD

pp dat

gr = dat.inject [] do |agg, rec|
   if agg.last && rec[1] - agg.last.last[1] <= 15
     agg.last << rec
     agg
   else
     agg << [rec]
   end
end

pp gr

Note: I don't claim that this is *the* Ruby way.

Kind regards

	robert

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/