【发布时间】:2014-08-28 22:55:30
【问题描述】:
我正在尝试对拓扑排序进行矢量化以加快运行速度
其中一部分是带有嵌套for 的while。我在矢量化时遇到问题。
这个函数的思想是对相互依赖的任务进行排序
这是我目前的代码:
tsort <- function(deps) {
nm <- names(deps)
libs <- union(as.vector(unlist(deps)), nm)
s <- c()
s <- unlist(lapply(libs,function(x){
if(!(x %in% nm)) {
s <- c(s, x)
}
}))
k <- 1
while(k > 0) {
k <- 0
for(x in setdiff(nm, s)) {
r <- c(s, x)
if(length(setdiff(deps[[x]], r)) == 0) {
s <- r
k <- 1
}
}
}
if(length(s) < length(libs)) {
v <- setdiff(libs, s)
stop(sprintf("Unorderable items :\n%s", paste("", v, sep="", collapse="\n")))
}
s
}
这里是一个可以用函数排序的相互依赖的任务列表:
tasks <- list(
"seven" = c("eight", "nine", "ten", "seven", "five", "one", "eleven", "two"),
"one" = c("two", "one", "three", "four"),
"five" = c("two", "five", "three"),
"six" = c("eight", "nine", "three", "six", "five", "one", "two", "four"),
"twelve" = c("twelve", "two", "one", "three", "four"),
"thirteen" = c("thirteen", "two", "three"),
"fourteen" = c("fourteen", "two", "three"),
"fifteen" = c("two", "three"),
"three" = c("two", "three"),
"four" = c("two", "four"),
"eleven" = c("eight", "two"),
"ten" = c("two", "ten"),
"nine" = c())
我要矢量化的部分是:
k <- 1
while(k > 0) {
k <- 0
for(x in setdiff(nm, s)) {
r <- c(s, x)
if(length(setdiff(deps[[x]], r)) == 0) {
s <- r
k <- 1
}
}
}
我发现很难对函数的主要部分进行矢量化,其中我有一个 for 和一个 while 一起
【问题讨论】:
-
我注意到您的代码中有语法错误。你有什么问题?
-
矢量化迭代过程随着时间的推移你会变得更好。它需要一种不同于你在编程时可能习惯的思维方式,而且一开始它看起来很陌生。如果没有适当的缩进,很难阅读您的代码,但我的建议总是从最深层次开始,然后向外移动。此外,检查可能预先计算的值、向量或矩阵,以减少混乱并简化有关向量化过程的推理。
-
你能解释一下你想用这段代码做什么吗?
-
@RichardScriven 它运行正常所以我认为没有任何语法错误
-
@josilber 这个函数用来对相互依赖的任务进行排序它是一个拓扑排序的代码,如 unix 的 tsort
标签: r vectorization graph-theory