I am looking for a nice way of flattening (splitting) a list of potentially-overlapping numeric ranges. The problem is very similar to that of this question: Fastest way to split overlapping date ranges, and many others.
However, the ranges are not only integers, and I am looking for a decent algorithm that can be easily implemented in Javascript or Python, etc.
Example Data:
Example Solution:
Apologies if this is a duplicate, but I am yet to find a solution.
Best Answer
Walk from left to right, using a stack to keep track of what color you're on. Instead of a discrete map, use the 10 numbers in your dataset as the break-points.
Starting with an empty stack, and setting
start
to 0, loop until we reach the end:start
, and push it and all lower-ranked colors onto the stack. In your flattened list, mark the beginning of that color.start
, and find the end of the current colorstart
to the end of this color, pop it off of the stack, and check the next-highest ranked colorstart
is within the next color's range, add this color to the flattened list, starting atstart
.This is a mental run-through given your example data: