javascript - 如何获得固定平均值的可能结果?

标签 javascript algorithm math dynamic-programming

我知道这个问题很难理解,但我需要一个 javascript 的数学方程式。

I am having dynamic number from 0 to 7.

现在我有 5 条记录:

a = from 0 to 7,
b = from 0 to 7,
c = from 0 to 7,
d = from 0 to 7,
e = from 0 to 7

现在我需要一个方程式,从中我可以找到 a、b、c、d 和 e 的可能输出,使平均值为 5。

Like for average = 5:
1. a = 5, b = 5, c = 5, d = 5, e = 5
2. a = 2, b = 7, c = 6, d = 5, e = 5

用户将输入所需的平均值,我需要抛出可能的输出以生成填充平均值。

最佳答案

这似乎是一个与整数规划相关的问题。它可以使用动态规划策略相对有效地解决,该策略为较小的子问题保持不变并将这些子问题合并为最终解决方案。这是一个可以帮助您实现目标的高级算法:

1) Start with a random seed number, x_1 between 0..7

2) Now do the following three times (i = 2, 3, 4) :

3) Find the minimally possible next number. To get an average of 5 for your five numbers, your target sum for all five is 25. So you need to ensure that you don't deny yourself the ability to reach 25 at all. So let min_i+1 determine the smallest number of 0..7 so that the sum of all x_i so far plus min_i+1 * (5-i) >= 25.

示例:假设 i=2,到目前为止你的数字是 4 和 5。那么最小允许的第三个数字 min_3 是 6。到目前为止的总和是 9 并且 5-i = 3。9 + 3*6 = 27 >= 25 和 9 + 3*5 = 24 < 25。这意味着如果您选择 5 作为 min_3,您将无法再达到总和为 25 的目标。

4) Choose x_i+1 as a random number between min_i+1 and 7.

5) Finally, choose x_5 as 25 - sum of x_1..x_5. Output x_1 to x_5.


整个算法的例子:

Let x_1 = 6.

=> min_2 = 5, sum = 6

Let x_2 = 5.

=> min_3 = 5, sum = 11

Let x_3 = 7.

=> min_4 = 4, sum = 18

Let x_4 = 5

=> sum = 23

=> x_5 = 2 (=25 - 23)

Output: [6, 5, 7, 5, 2] which indeed has an average of 5.

现在这个算法会产生非常有偏见的输出,如果你想让它更随机地出现,只需提供最终结果的排列,例如在我们的示例中,您可以改为输出 [5, 7, 2, 5, 6]。

用 Javascript 实现它应该没有问题,它可以很容易地适应 x_i 和总平均值的其他可能范围。如果您的最终样本量应为 n 且平均值为 avg,请务必将目标总和修改为 n * avg。

关于javascript - 如何获得固定平均值的可能结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9716876/

相关文章:

algorithm - 有没有创新的水印技术,水印不明显?

c++ - 中缀的前缀不能完全给出正确的结果

javascript - 在两个重叠椭圆形状区域内生成随机点

javascript - 每个对象?

c++ - 使用动态规划创建最大配置

javascript - ajax请求后脚本不再工作

python - Scipy linalg LU 分解为我的教科书提供了不同的结果

javascript - 反转游戏经验公式以显示一个级别需要多少经验

javascript - 这段代码使用 typeof … != "undefined"和clearInterval 做什么?

javascript - 用于选择集合中 'Shift + Clicking' 项的算法