[英]recursive function in R
我想了解这个问题。 在for
语句之后,我不再理解。
这是一个递归程序(打印所有可能的方式,以使用澳大利亚硬币(5、10、20、50、100和200分面额)组成x(以分为单位)。 每个分解都是有序的。
change <- function(x, y.vec = c()) {
# finds possible ways of making up amount x using Australian coins
# x is given in cents and we assume it is divisible by 5
# y.vec are coins already used (so total amount is x + sum(y.vec))
if (x == 0) {
cat(y.vec, "\n")
} else {
coins <- c(200, 100, 50, 20, 10, 5)
new.x <- x - coins
new.x <- new.x[new.x >= 0]
for (z in new.x) {
y.tmp <- c(y.vec, x - z)
if (identical(y.tmp, sort(y.tmp))) {
change(z, y.tmp)
}
}
}
return(invisible(NULL))
}
重写该程序,以便将其输出作为列表而不是将其输出写入屏幕,其中每个元素都是一个向量,可能分解x。
由于该算法每次都会在循环中考虑每个硬币,因此有可能针对同一组硬币得出多个结果(例如35 = 5 + 10 + 20 = 5 + 20 + 10 = 10 + 20 + 5是相同答案的三种不同方式)。 循环内的逻辑确保答案仅给出一次, if (identical(y.tmp, sort(y.tmp)))
从低到高的硬币排序,因为if (identical(y.tmp, sort(y.tmp)))
仅在第一次遇到时为TRUE
。 (用change(z, c(y.vec, x - z))
替换循环内部的逻辑change(z, c(y.vec, x - z))
以查看差异)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.