Closest pair for any of a huge number of points

后端 未结 3 1691
天命终不由人
天命终不由人 2020-12-22 02:37

We are given a huge set of points in 2D plane. We need to find, for each point the closest point within the set. For instance suppose the initial set is as follows:

3条回答
  •  轮回少年
    2020-12-22 03:03

    Here is an example; all wrapped into a single function. You might want to split it a bit for optimization.

    ClosesPair <- function(foo) {
      dist <- function(i, j) {
        sqrt((foo[i,1]-foo[j,1])**2 + (foo[i,2]-foo[j,2])**2)
      }
    
      foo <- as.matrix(foo)
    
      ClosestPoint <- function(i) {  
        indices <- 1:nrow(foo)
        indices <- indices[-i]
    
        distances <- sapply(indices, dist, i=i, USE.NAMES=TRUE)
    
        closest <- indices[which.min(distances)]
      }
    
      sapply(1:nrow(foo), ClosestPoint)
    }
    ClosesPair(foo)
    # [1] 2 1 4 3 3
    

    Of cause, it does not handle ties very well.

提交回复
热议问题