帮我找一个好的算法吗?
我有一个装有n个球的袋子。 (以28个球为例)
这个袋子里的每个球都有一种颜色。袋子里最多有4种不同颜色的球。(例如,红色,绿色,蓝色和紫色是可能的颜色。)
我有三个桶,每个桶都有一个数字,表示它们需要最终拥有的球的数量。这些数字总共为n。(例如,假设桶A需要最终拥有7个球,桶B需要最终拥有11个球,桶C需要最终拥有10个球。)
这些桶也可能有颜色限制 - 它们不接受的颜色。(桶A不接受紫色球或绿色球。桶B不接受红色球。桶C不接受紫色球或蓝色球。)
我需要有效且随机地分配这些球(所有可能性的概率相等)。
我不能只是将球随机放在有空间可以接受它们的桶中,因为那可能会导致出现这样一种情况:唯一有剩余空间的桶不接受袋子中仅剩的颜色。
已知总是有至少一种分配球的可能性。(我不会拥有只有红色球的袋子,而某个数量> 0的桶不接受红色球。)
即使它们是相同的颜色,所有球都被认为是不同的。(桶C获得红球1而不是红球2的可能性之一与除了桶C获得红球2而不是红球1之外其他所有内容相同的可能性是不同的。)
编辑以添加我的想法:
我不知道这是否具有所有可能性的等概率性,因为我希望如此。我还没有找出效率 - 它似乎不太糟糕。并且这包含一个我不确定是否始终正确的断言。如果您知道任何这些事情,请在评论中提出意见。
Choose a ball from the bag at random. (Call it "this ball".)
If this ball fits and is allowed in a number of buckets > 0:
Choose one of those buckets at random and put this ball in that bucket.
else (this ball is not allowed in any bucket that it fits in):
Make a list of colors that can go in buckets that are not full.
Make a list of balls of those colors that are in full buckets that this ball is allowed in.
If that 2nd list is length 0 (There are no balls of colors from the 1st list in the bucket that allows the color of this ball):
ASSERT: (Please show me an example situation where this might not be the case.)
There is a 3rd bucket that is not involved in the previously used buckets in this algorithm.
(One bucket is full and is the only one that allows this ball.
A second bucket is the only one not full and doesn't allow this ball or any ball in the first bucket.
The 3rd bucket is full must allow some color that is in the first bucket and must have some ball that is allowed in the second bucket.)
Choose, at random, a ball from the 3rd bucket balls of colors that fit in the 2nd bucket, and move that ball to the 2nd bucket.
Choose, at random, a ball from the 1st bucket balls of colors that fit in the 3rd bucket, and move that ball to the 3rd bucket.
Put "this ball" (finally) in the 1st bucket.
else:
Choose a ball randomly from that list, and move it to a random bucket that is not full.
Put "this ball" in a bucket that allows it.
Next ball.