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

  • 本文关键字:解决 硬币 问题 r
  • 更新时间 :
  • 英文 :


美元中有四种常见的硬币:

季度(25美分(一角硬币(10美分(五分硬币(5美分(,以及便士(1美分(

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

一角硬币和五分硬币一角硬币和五便士3个镍币2美分和5便士一枚五分硬币和10便士15便士

任务:

有多少种方法可以用这些常见的硬币兑换一美元?(1美元=100美分(。

tl;dr
在1、5、10和25美分的无限供应中,有242种可能性可以赚到1美元。

代码
这里有一个使用RcppAlgos-包中的comboGeneral()-函数的尝试。

只需将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_contraint=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_contraint=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

最新更新