Search code examples
algorithmconflict

Resolving the stacking order of overlapping items


I have a list of Foo with these properties:

class Foo
(
    Date From
    Date To
    int Importance
)

The From and To dates of these items can overlap. Where two foos overlap, the foo with the highest Importance overrides the other items.

Is there an elegant algorithm to take a list of Foo and resolve any overlaps (by determining which Foo has the highest Importance factor) using the above rules? My attempts so far have been ugly. Ultimately they come down to a series of checks for each possible overlapping conflict, such as a higher priority preceding a lower priority foo, a higher priority foo appearing in the middle of the range of a lower priority foo, and so on. Such a strategy looks unmaintainable and begs for a more elegant approach that I haven't yet found.

The big issue here is that a higher priority Foo can subdivide a lower priority one, so we can't simply adjust the From and To points of conflicting Foos.


Solution

  • You can use a priority queue.

    1. Generate all triples (Date, bool, int), where the first argument is a To or From property of one of the Foos and bool indicates whether it's a To (true) or From (false) and the int one is the priority.
    2. Sort the list of those pairs by Date
    3. Create an empty priority queue of of triples ordered by Importance.
    4. Iterate over the sorted list and for each triple (date, isTo, importance) do:

      a. If it's a From (isTo=false) then add to the queue

      b. If it's a To (isTo=true) then remove from the queue

    At any time the max element in the queue (which you can lookup in O(1)) contains the one who wins for that time.

    (If you need the actual Foo object, just make the triple a 4-tuple with a reference to the Foo).