[英]How many different ways to fill N number bins with B number of balls
Assume you have N number of bins, where the capacity of each in bin is K. You also have B number of balls. 假设您有N个箱,其中每个箱的容量为K。您还有B个球。 How many different ways can all the balls be distributed into the bins?
所有的球可以有多少种不同的方式分配到垃圾箱中?
I'm trying to solve this problem by writing a function that takes in the following parameters: 我正在尝试通过编写一个采用以下参数的函数来解决此问题:
public static int waysBin(int ball, int bin, int capacity)
{
//code here
}
I'm a bit unsure as to how to approach this. 我不确定如何解决这个问题。 I know when N = 0, the answer is 0. And when B = 0, N> 1, the answer is 1.
我知道当N = 0时答案为0。而当B = 0时N> 1时答案为1。
However, I'm not sure of how to calculate it for every other combination. 但是,我不确定如何对其他所有组合进行计算。 I'd like to solve this both recursively and dynamically.
我想以递归和动态的方式解决这个问题。
Think of it this way: if you have n balls filling b bins of capacity k then you can fill the first bin with between 0 and k balls (call that number c). 这样想:如果您有n个球填充b个容量为k的箱,那么您可以用0到k个球填充第一个箱(称为数字c)。 For each of these possibilities you can fill the remaining b-1 bins with nc balls.
对于每种可能性,您都可以用nc球填充其余的b-1箱。 If you have only 1 bin then there is one combination if you have fewer balls than the capacity, zero otherwise.
如果您只有1个垃圾箱,那么如果球数少于容量,则只有一种组合,否则为零。
So: 所以:
int combinations(int ballCount, int binCount, int binSize) {
if (binCount > 1) {
return IntStream.rangeClosed(0, Math.min(ballCount, binSize))
.map(c -> combinations(ballCount - c, binCount - 1, binSize))
.sum();
} else {
return binCount == 0 || ballCount > binSize ? 0 : 1;
}
}
If you do not have Java 8 use: 如果您没有Java 8,请使用:
int combinations(int ballCount, int binCount, int binSize) {
if (binCount > 1) {
int combos = 0;
for (c = 0; c <= Math.min(ballCount, binSize); c++)
combos += combinations(ballCount - c, binCount - 1, binSize);
return combos;
} else {
return binCount == 0 || ballCount > binSize ? 0 : 1;
}
}
An idea: 一个主意:
Make a class to represent a Bin. 制作一个类来代表Bin。 It will have an int representing how many balls are inside it.
它将有一个int表示其中有多少个球。
Make a class called BinState. 创建一个名为BinState的类。 It will have a List of bins with length N.
它将具有长度为N的垃圾箱列表。
Then a recursive function that will look like this. 然后,一个递归函数将如下所示。 Warning, it's untested.
警告,未经测试。
int waysBin(int num_balls, BinState binState) {
int ways = 0;
for (int i = 0; i < binState.numberofbins(); i++) {
BinState deepCopyOfBinState = ?;
/* I don't know how to make a deep copy in java.
You will need to make a deep copy because this
function modifies the deep copy (adding a ball)
*/
Bin indexedBin = deepCopyOfBinState.getBinNumber(i);
if (indexedBin.isUnderCapacity()) {
indexedBin.addOneBall();
ways += waysBin(num_balls-1, deepCopyOfBinState);
} else {
ways += 1; // maybe
}
}
return ways;
}
Then you call the recursive function from the function you wrote above. 然后,您从上面编写的函数中调用递归函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.