【问题标题】:Smallest sub-vector with all distinct values of the original vector具有原始向量的所有不同值的最小子向量
【发布时间】:2018-11-15 19:29:37
【问题描述】:

假设我们有一个长度为 n 且具有 k 个不同值的向量。

{1, 4, 2, 2, 3, 4, 1, 1, 5, 2, 2}

如何找出具有原始向量的所有不同值的值、序列和频率的最小子集的开始和结束坐标(在原始向量上)?

对于我们的示例,子集将是

{2, 3, 4, 1, 1, 5}

开始和结束坐标分别是49

【问题讨论】:

  • 既然这是 R 并且您花时间制作一个数字序列,为什么 {}c()?蜘蛛侠说#homework
  • 哈哈不,我只是习惯性地使用集合符号。我在写问题时编造了顺序,没有抄袭。

标签: r vector


【解决方案1】:

这里有一些可以完成这项任务的东西:首先我创建一个向量index,其中index[k] 等于要走的索引数量(从k 开始),直到一个人至少拥有所有元素一次,如果情况并非如此,则它等于Inf

# determining the unique elements of v
uniqueVals <- unique(v)
index <- numeric(length(v))

# helper function
myFun <- function(k){
   helper <- vapply(seq(k, length(v)), 
                    function(s) length(setdiff(uniqueVals, v[k:s])), 
                    numeric(1))
   return (ifelse(min(helper) == 0, which.min(helper)-1, Inf))
}

# indices in seq1 must be infinity as there are not enough values left
seq1 <- which(length(v) - seq_along(v) < length(uniqueVals))
index[seq1] <- Inf
# for the other indices we now use our helper function
index[seq(1, min(seq1)-1)] <- vapply(seq(1, min(seq1)-1), myFun, numeric(1)) 

# applying the above
startIndex <- which.min(index) 
endIndex <- index[startIndex] + startIndex
v[startIndex:endIndex]
# yielding
[1] 2 3 4 1 1 5

其中v = c(1, 4, 2, 2, 3, 4, 1, 1, 5, 2, 2) 和任何给定的k myFun 将返回最小的数字n 使得v[k:n] 包含v 的每个元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-01
    • 1970-01-01
    • 2015-10-11
    相关资源
    最近更新 更多