1

I have array similar to this

[
 [0, 10]**,
 [1, 3]**,
 [5, 11]**,
 [14, 20]**,
 [10, 11]**
]

** Denotes an object containing the start and end indexes shown in the array

Now, the intersections are [1, 3], [5,10], [10,11]

What is the best way to write a method that returns the objects containing of the intersecting sets? (Could just store them in an array of conflicted stuff as we go along)

The biggest issue I'm having is how do I do this such that each object is compared with eachother object?

there are n! ways to do this (i think, I'm a bit rusty on my combinatorics)

Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
NullVoxPopuli
  • 61,906
  • 73
  • 206
  • 352

1 Answers1

0

Sort the intervals by start time (or instead sort an array of indices by start time so you don't lose the indices).

After this you can do a single pass detecting all intersections/conflicts.

Range array[N];

sort(array);
int i=0;
while(i<N){
    Range curr = array[i];  //invariant: curr doesn't intersect with anyone befor it
    i++;
    while(i < N && array[i].start <= curr.end){
        output that curr and array[i] intersect;
        if(array[i].end > curr.end){
            curr = array[i]
        }
        i++;
    }
}
hugomg
  • 68,213
  • 24
  • 160
  • 246
  • Unless I'm misunderstanding, this is the "selection sort" method, right? Compare each range with all ranges below it, with an early out testing start time against curr_end. – Jim Mischel Oct 31 '11 at 21:09
  • I don't quite understand this, could you explain a bit better? you are using a stack. =\ Oh, and I should say the indexes are as important, as this is actually an array of objects that have a start and end index. I'll update my question, as it is relevant. – NullVoxPopuli Oct 31 '11 at 21:10
  • ehm.. not quite. you have too keep the biggest `.end`, otherwise you can miss intersections. – Karoly Horvath Oct 31 '11 at 21:22
  • is this the most efficent way to do this? i mean, it looks like O(n^n) – NullVoxPopuli Nov 01 '11 at 13:18
  • It looks O(n) to me. You start with i=0 and i goes up to N one by one. (note how each array element is processed only once) – hugomg Nov 01 '11 at 13:21