Thursday, 15 July 2010

algorithm - Find set difference between two integer intervals -



algorithm - Find set difference between two integer intervals -

i've faced problem. had find set difference between 2 integer intervals. interval determined 2 borders - high , low. high point isn't included.

well came solution, consider several cases. of sudden it's ~12 cases. listed of them below. looks wierd. there simpler solution?

//a[ a) b[ b) // [ ) if (a._end <= b._start) homecoming lst(a); //a[ b[ a) b) // [ ) if (a._start < b._start && b._start < a._end && b._start < a._end && a._end < b._end) homecoming lst(rng(a.start(), b.start())); //b[ a[ b) a) // [ ) if (b._start < a._start && a._start < b._end && a._start < b._end && b._end < a._end) homecoming lst(rng(b.end(), a.end())); //b[ b) a[ a) // [ ) if (b._end <= a._start) homecoming lst(a); //a[ b[ b) a) // [ ) [ ) if (a._start < b._start && b._start < a._end && a._start < b._end && b._end < a._end) homecoming lst( rng(a.start(), b.start()), rng(b.end(), a.end()));

(i don't see why decided generate such redundant conditions ... b._start < a._end && b._start < a._end ...)

among other things, code made more complicated attempts build entire result within single homecoming statement. if build result incrementally in local variable , homecoming local variable, code simplified.

relying on standard functions min , max instead of embedding min/max logic code create much more compact.

let's build result in local list variable result , append intervals doing result.append().

the difference operation can produce 2 intervals: 1 left of b, right of b. let's calculate them in order

list result; if (a._start < b._start) // left portion exists result.append(rng(a._start, min(a._end, b_start))); if (a._end > b._end) // right portion exists result.append(rng(max(a._start, b._start), a._end)); homecoming result;

i assumed intervals normalized, i.e. a._start <= a._end, seems code relies on assumption.

algorithm

No comments:

Post a Comment