问题描述
我们有一定数量,例如300个单位.该数量应尽可能均匀地分布在40个插槽"或箱"中.如果每个插槽都相同,这将很容易-因此每个插槽将为7.5.但是,这些插槽的大小各不相同,我们不能在其中填充"超过其大小"所允许的数量,例如如果只有4个.我们不能填充"超过4个.因此,我们必须在其他分布上分配更多.
We have have a certain amount e.g. 300 units. This amount should be as evenly as possible distributed over 40 "slots" or "bins". It would be easy if each slot would be the same - so it would be 7,5 at each slot. However, the slots vary in size and we cannot "fill in" there more than its "size" allows for e.g. if its only 4. What we cannot "fill in" more than 4. Hence, we have to distribute more over the other ones.
让我们假设还有另一个限制:一般填写的限制为5.这意味着即使我们在插槽中有足够的大小来填充(例如12),而剩余的剩余单元数(例如11),我们也只能填充5.将所有插槽填充后的剩余值放在一个单独的位置剩余插槽.在每次填充过程中,我们还应该获得一个数字,以百分比表示最大填充容量的使用量. IE.如果我们填写4和5是一般的填充限制.我们用了80%.
Lets assume that there is another limitation: A general filling in limit of e.g. 5. That would mean that even if we have enough size in the slot to fill in say 12 and enough units remaining say 11, we can only fill in 5. The value that is excess after all slots are filled should be placed in a seperated remainder slot.With each filling in process we should also get a number how much of the maximum-filling in capacity in percent is used. I.e. if we fill in 4 and 5 is the general filling limit. We used 80%.
我们在前面的另一个问题中已经讨论了这一点:尽可能平均地分配金额
We discussed this already earlier in anohter question:Distributing an amount as evenly as possible
我有一些想法如何进一步发展这个公式,但是仍然有一部分卡住了.感谢您的帮助!
I have some ideas how do develop this formula further, however partially it still stucks.Thanks for your help!
# developing slots and their "size"
a <- rnorm(40,10,4)
sum(a)
# overall sum to distribute
b <- 300
# general filling in limit
c <- 8
optimal.fill <- function(a, b)
{
stopifnot(sum(a) >= b)
d <- rep(0, length(a))
info <- rep(0, length(a))
while(b > 0) {
has.room <- a > 0
num.slots <- sum(has.room)
min.size <- min(a[has.room])
add.size <- min(b / num.slots, min.size)
#maximum limitation
add.size[add.size>c] <- c
#percentage info
info[has.room] <- add.size/c
d[has.room] <- d[has.room] + add.size
a[has.room] <- a[has.room] - add.size
b <- b - num.slots * add.size
}
return(d)
}
optimal.fill(a,b)
推荐答案
如何解决
optimal.fill <- function(a, b, generalLimit = 8){
a <- pmax(0, pmin(a, generalLimit))
if(sum(a) < b){
stop("not enough room")
}
if(length(a) * min(a) <= b){
result <- rep(min(a), length(a))
} else {
result <- rep(floor(b / length(a)), length(a))
}
while(floor((b - sum(result)) / sum(result < a)) >= 1){
if(min(a[result < a]) * sum(result < a) <= b - sum(result)){
result[result < a] <-
result[result < a] + rep(min(a[result < a]), sum(result < a))
} else {
result[result < a] <-
result[result < a] +
rep(floor((b - sum(result)) / sum(result < a)), sum(result < a))
}
}
extra <- sample(which(result < a), (b - sum(result)), replace = FALSE)
result[extra] <- result[extra] + 1
return(cbind(result, result / a))
}
optimal.fill(ceiling(rnorm(40,10,4)), 300, 8)
这篇关于R:尽可能平均地分配金额II的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!