The subject line is a mouthful, but assuming the following scenario, I’m
looking for an elegant way to accomplish the following:
We have an array which contains n-number of elements which themselves
are arrays of ranges (these are ranges of UNIX timestamps - start/end
times, but that’s not important) - let’s assume a single array
containing three arrays of ranges.
I need to find the intersections, if any exists where the ranges
overlap/intersect across all (in this case 3) arrays of ranges.
I have a simple solution with nested foreach type loops, but I’m looking
for a way to handle it differently, and to allow for a variable number
of arrays of ranges.
I have a method that compares two ranges, determines if they overlap in
any way, and returns either a new range that represents the overlap
range, or nil if there is no overlap in the two, so we can assume I have
that part taken care of.
Any thoughts?
Example of the mentioned intersection method:
class Range
def intersection(other)
my_min, my_max = first, exclude_end? ? max : last
other_min, other_max = other.first, other.exclude_end? ? other.max :
other.last
new_min = self === other_min ? other_min : other === my_min ? my_min
: nil
new_max = self === other_max ? other_max : other === my_max ? my_max
: nil
new_min && new_max ? new_min…new_max : nil
end
alias_method :&, :intersection
end
def get_range_overlap(r1, r2)
intersection_range = r1.intersection(r2)
intersection_range != nil ? intersection_range : nil
end