有很多方法可以做到这一点。这是一个。
从你比水桶开始。如果您有超过 2 个,则没有解决方案。否则,将地板分配给他们每个人(在您的示例中为 0.4)。
接下来,将每个存储桶视为有一个上限。给出了低于。对于higher_thans,使用比higher_than少1.0(这里是0.6)。
记录 rand() * 每个桶的上限。重新调整这些以等于初始分配给higher_than存储桶后剩余的容量,然后完成分配。
例如,假设我们有两个上限为 0.1、两个上限为 0.2、一个下限为 0.4。
1. allocate weight to the higher_than bucket.
weights = [0.0, 0.0, 0.0, 0.0, 0.4] (buckets in order I listed them)
2. rand() * cap:
unscaled allocation = [0.73 * 0.1, 0.24 * 0.1, 0.34 * 0.2, 0.87 * 0.2, 0.33 * 0.6] = [0.073, 0.024, 0.068, 0.174, 0.198]
现在缩放有点棘手,因为天真的方法,按期望分配与当前分配的比率缩放所有内容,有超过 lower_than 上限的风险。
通过将缩放因子应用于 caps 数组来处理此问题 - 未缩放的分配。 IE。 [0.1 - 0.073, 0.1 - 0.024, 0.2 - 0.068, 0.2 - 0.174, 0.6 - 0.198] = [0.027, 0.076, 0.132, 0.026, 0.402]
我们想用它来缩放未缩放的分配数组,使其总和为 0.6。目前它的总和为 0.537,而 caps_less_allocation 数组的总和为 0.663。我们需要将我们的分配增加 0.6 - 0.537 = 0.063。所以我们将 caps_less_allocation 数组中的所有内容乘以 0.063/0.663,然后将我们的三个数组相加:
[0.0, 0.0, 0.0, 0.0, 0.4] - initial weight array
[0.073, 0.024, 0.068, 0.174, 0.198] - unscaled allocation array
[0.00257, 0.00722, 0.01254, 0.00247, 0.03820] - additive scaling factors (rounded)
---------------------------------------------------------------------
[0.07557, 0.03122, 0.08054, 0.17647, 0.63620]
现在我们有一个满足我们的约束并且总和为 1.0 的随机数组