简体   繁体   English

R中的递归函数

[英]recursive function in R

I want to understand this problem. 我想了解这个问题。 I stop understanding after the for statement. for语句之后,我不再理解。

This is a recursive program (prints all the possible ways that an amount x (in cents) can be made up using Australian coins (5, 10, 20, 50, 100, and 200 cent denominations)). 这是一个递归程序(打印所有可能的方式,以使用澳大利亚硬币(5、10、20、50、100和200分面额)组成x(以分为单位)。 Each decomposition is ordered. 每个分解都是有序的。

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))
}

Rewrite this program so that instead of writing its output to the screen it returns it as a list, where each element is a vector giving a possible decomposition of x. 重写该程序,以便将其输出作为列表而不是将其输出写入屏幕,其中每个元素都是一个向量,可能分解x。

Since the algorithm considers every coin every time through the loop, it would be possible to come up with multiple results for the same set of coins, (for example 35 = 5+10+20 = 5+20+10 = 10+20+5 are the same answer three different ways). 由于该算法每次都会在循环中考虑每个硬币,因此有可能针对同一组硬币得出多个结果(例如35 = 5 + 10 + 20 = 5 + 20 + 10 = 10 + 20 + 5是相同答案的三种不同方式)。 The logic inside the loop ensures the answer is only given once, sorted by low to high value coins, since if (identical(y.tmp, sort(y.tmp))) evaluates to TRUE only once, the first time it is encountered. 循环内的逻辑确保答案仅给出一次, if (identical(y.tmp, sort(y.tmp)))从低到高的硬币排序,因为if (identical(y.tmp, sort(y.tmp)))仅在第一次遇到时为TRUE (Replace the logic inside the loop with change(z, c(y.vec, x - z)) in order to see the difference). (用change(z, c(y.vec, x - z))替换循环内部的逻辑change(z, c(y.vec, x - z))以查看差异)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM