Skip to content
Prev 280738 / 398503 Next

Union/Intersect two continuous sets

??? <cutexym <at> gmail.com> writes:
I got interested in your request as I could use it myself (not for intervals,
but a similar kind of problem).
I assume, you represent your set of intervals as a matrix M with two columns,
first column the left endpoints, second the right ones.

Intersection is easy, as it is the interval from the maximum of left end
points to the minimum of the right end points (or NULL if the maximum is
greater than the minimum).

For the union I didn't see a simple, i.e. one or two lines, solution ahead,
so here is my dumb, looped version. Surely there are more elegant solutions
coming.

    # Mnew the union of intervals in M, an (nx2)-matrix with n > 1:
    o <- order(M[, 1], M[, 2])
    L <- M[o, 1]; R <- M[o, 2]
    k <- 1
    Mnew <- matrix(c(L[k], R[k]), 1, 2)
    for (i in 2:nrow(M)) {
        if (L[i] <= Mnew[k, 2]) {
            Mnew[k, 2] <- max(R[i], Mnew[k, 2])
        } else {
            k <- k+1
            Mnew <- rbind(Mnew, c(L[i], R[i]))
        }
    }

    # Inew the intersection of intervals in M, an (nx2)-matrix with n > 1:
    L <- max(M[, 1]); R <- min(M[, 2])
    Inew <- if (L <= R) c(L, R) else c()