【问题标题】:Find pairwise overlaps of intervals (segments)查找区间(段)的成对重叠
【发布时间】:2013-08-17 09:25:28
【问题描述】:

我们有两组区间AB。间隔是指一对有序整数,例如c(2,5)。我想找到所有有重叠的间隔对——一个来自A,一个来自B

例如如果A和B如下:

A=c(c(1,7), c(2,5), c(4, 16))
B=c(c(2,3), c(2,20))

那么FindOverlap(A, B) 应该返回一个如下所示的矩阵(唯一的零元素是因为A 的第三个区间与B 的第一个区间不重叠):

1 1
1 1
0 1

你有什么有效的想法吗?

【问题讨论】:

    标签: r performance algorithm intervals segments


    【解决方案1】:

    interval 包似乎在这里提供了一个解决方案:

    require("intervals")
    A <- rbind(A1=c(1,7), A2=c(2,5), A3=c(4, 16))
    B <- rbind(B1=c(2,3), B2=c(2,20))
    
    # here you can also define if it is an closed or open interval
    Aint <- Intervals(A)
    Bint <- Intervals(B)
    
    # that should be what you are looking for    
    interval_overlap(Aint, Bint)
    

    A nice demonstration

    【讨论】:

      【解决方案2】:

      这是我写的一个小函数来做同样的事情。它可以大幅改进。不过有趣的问题。

      f <- function(A,B){
        tmpA <-  lapply( A , function(x) min(x):max(x) )
        tmpB <-  lapply( B , function(x) min(x):max(x) )
        ids <- expand.grid( seq_along( tmpA ) , seq_along( tmpB ) )
        res <- mapply( function(i,j) any( tmpA[[i]] %in% tmpB[[j]] ) , i = ids[,1] , j = ids[ ,2] )
        out <- matrix( res , nrow = length( tmpA ) )
        return( out * 1 )
        }
      
       f(A,B)
           [,1] [,2]
      [1,]    1    1
      [2,]    1    1
      [3,]    0    1
      

      【讨论】:

      • 感谢您的回答。这是一个仅使用基本 R 功能的有趣想法,尽管时间复杂度为 O(n * m * p),其中 n 是 A 中的项目数,m 是 B 中的项目数,p 是最大长度一个间隔。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-29
      • 2014-11-07
      • 1970-01-01
      • 2014-06-06
      相关资源
      最近更新 更多