tl; др
Существует 242 возможности заработать 1 доллар из неограниченной поставки по 1, 5, 10 и 25 центов.
код
Здесь мы рассмотрим использование функции 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