[英]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.