使用R时,有人能解决硬币问题吗?

时间:2019-11-05 14:02:20

标签: r

有四种普通的美元硬币:

季度(25美分)   角钱(10美分)   镍币(5美分),以及   便士(1美分)

有六种方法可以改变15美分:

一角钱和镍   1角钱和5便士   3镍   2镍5便士   一分钱和十便士   15便士

任务:

使用这些通用硬币有多少种方式可以兑换一美元? (1美元= 100美分)。

1 个答案:

答案 0 :(得分:2)

tl;博士
从1,2,5,10和25美分的无限制供应中赚取1美元,有242种可能性。

代码
这是使用comboGeneral()软件包中的RcppAlgos函数进行的。

只需将sum_constraint设置为您希望硬币值相加的总和。

library(RcppAlgos)
library(data.table)

# possible coin-values
vec <- c( 1, 5, 10, 25 )
#desired sum
sum_constraint <- 15

l <- lapply( 1:sum_constraint / min(vec) , function(x) {
  #calculate possible combinations (output = matrix)
  temp <- comboGeneral( vec, 
                        m = x, 
                        repetition = TRUE, 
                        constraintFun = "sum",
                        comparisonFun = "==", 
                        limitConstraints = sum_constraint )
  #create rowwise frequency-table of the freshly created matrix,
  #and convert the table to a data.frame
  as.data.frame.matrix( table( c( row(temp)), c(temp) ) )
  })

#bind the list together to a data.table
answer <- rbindlist(l, idcol = "no_coins", use.names = TRUE, fill = TRUE )
#set missing values to 0
answer[ is.na(answer) ] <- 0
#output
answer

sum_constraint = 15

#    no_coins 5 10  1
# 1:        2 1  1  0
# 2:        3 3  0  0
# 3:        6 0  1  5
# 4:        7 2  0  5
# 5:       11 1  0 10
# 6:       15 0  0 15

sum_constraint = 100

#    no_coins 25 5 10   1
# 1:        4  4 0  0   0
# 2:        6  3 1  2   0
# 3:        7  3 3  1   0
# 4:        7  2 0  5   0
# 5:        8  3 5  0   0
# ---                     
# 238:       88  0 3  0  85
# 239:       91  0 0  1  90
# 240:       92  0 2  0  90
# 241:       96  0 1  0  95
# 242:      100  0 0  0 100
#      no_coins 25 5 10   1