Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# a possible solution for http://www.ruby-forum.com/topic/206291
class Record
# might choose to have it return
def self.group_by_time( records )
records = records.sort_by { |r| r.time }
groups = Array.new
# each consecutive record must be the smallest of the ungrouped records
# and we know the last group must be the greatest of the grouped records
# so we can compare each record to the last group to see if it belongs
records.each do |record|
group = groups.last
if groups.empty? || group[:max] < record.min # if we need to make a new group
groups << Hash[ :min,record.min , :max,record.max , :records,[record] ] # create it: a hash with the min, max, and records array
else # if it fits into the last group
group[:max] = record.max
group[:records] << record
end
end
groups.map { |group| group[:records] }
end
attr_accessor :name , :time
def initialize(name,time)
self.name , self.time = name , time
end
def inspect
name
end
def max
time + 30
end
def min
time - 30
end
end
def parse_records(raw_records)
raw_records.split("\n").map do |raw_record|
name , time = raw_record.split
Record.new name , time.to_i
end
end
records = parse_records <<END_OF_RECORDS
A 0
F 215
C 35
G 300
D 100
E 205
B 15
END_OF_RECORDS
puts "the ungrouped records: #{records.inspect}"
grouped = Record.group_by_time(records)
puts "the grouped records: #{grouped.inspect}"
puts "The other test group: #{Record.group_by_time(parse_records <<END_OF_RECORDS).inspect}"
A 0
B 20
C 40
END_OF_RECORDS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment