【发布时间】:2016-07-04 15:59:59
【问题描述】:
我首先要说的是,这种问题可能有一个名字,我根本不知道它的名字。
解释:
有 8 个球槽和 100 个球在槽之间随机分配。有 3 种不同类型的插槽:红色、绿色和蓝色。红色插槽类型必须至少有 6 个球,绿色 15 和蓝色无关紧要。
除了每种不同颜色所需的数量外,还可能有多个红色、绿色或蓝色插槽,每个插槽的进球率相同。红色是 4%,绿色是 15%,蓝色是其余未被选中的。
所以随机建议一个序列这是一种可能性:
Slot 1 - Blue with 17 balls
Slot 2 - Green with 8 balls
Slot 3 - Green with 12 balls
Slot 4 - Red with 1 ball
Slot 5 - Blue with 33 balls
Slot 6 - Red with 7 balls
Slot 7 - Blue with 12 balls
Slot 8 - Green with 10 balls
请注意,所需数量已被填满,并且还有不止一个红色和绿色插槽,尽管它只需要一个(至少里面的球总数)。
我需要的是一个伪代码或任何语言的代码,显示如何在不同的插槽和不同的重量之间分配所有 100 个球。我一直在编程,但每 3 次运行,一次未能分配每一个球,它错过了一些。
--编辑: 我用 C# 制作的代码草图(这只是彩色插槽生成):
int amountOfRedSlots = 0, amountOfGreenSlots = 0, amountOfBlueSlots = 0;
int[] slotColors = new int[8]; //1 - red, 2 - green, 3 - blue;
for(int i = 0; i < 8; i++)
{
int num = Random.Range(1, 101);
if (num <= 4) //Spawn a redSlot
{
amountOfRedSlots++;
slotColors[i] = 1;
}
else if (num <= 19) //4 numbers excluded from not being a redSlot and 15 as percentage to be green
{
amountOfGreenSlots++;
slotColors[i] = 2;
}
else
{
amountOfBlueSlots++;
slotColors[i] = 3;
}
}
if (amountOfRedSlots < 1)
{
int rand = Random.Range(1, 9); //Choose a random slot to be red
if (slotColors[rand] == 2)
{
amountOfGreenSlots--;
} else amountOfBlueSlots--;
slotColors[rand] = 1;
amountOfRedSlots++;
}
if (amountOfGreenSlots < 1)
{
int rand;
do
{
rand = Random.Range(1, 9);
} while (slotColors[rand] == 1); //Choose a random slot to be green, but it can't be a former red slot
amountOfBlueSlots--; //Since there isn't a greenSlot, and we made sure it wasn't red, its certainly a former blue slot
slotColors[rand] = 2;
amountOfGreenSlots++;
}
//Now its needed to distribute the balls between the slots, giving the required minimum amount to be inside red slots and green slots
//Also note that there is smaller chance of a ball going inside a red/green slot (4% and 15%)
【问题讨论】:
-
你能显示你目前尝试过的代码吗? Stack Overflow 不是代码编写服务。
-
我确实理解你的说法,我说过需要代码,但我真正需要的只是解决方案的一些指导,也许是一些步骤。我编写的代码有 200 多行,非常未经优化。
-
我不明白关于多个红色和绿色插槽类型的要求。必须有一个红色槽,因此槽为红色的概率必须至少为 12.5%,远高于 4%。
-
我不明白你从哪里拿走了 12.5%,但解释是:由于红色槽内需要至少 6 个球,因此必须至少有一个,但不是强制性的只是一个。
标签: c algorithm random pseudocode