gpt4 book ai didi

javascript - 将数字分成 4 个随机数

转载 作者:数据小太阳 更新时间:2023-10-29 03:58:51 26 4
gpt4 key购买 nike

我想将 10 分成一个由 4 个随机数组成的数组,但不能是 0 或大于 4。例如 [1,2,3,4][1,4,4,1][4,2,3,1].

我认为这是一个简单的问题,但出于某种原因我想不出该怎么做。如果有人有一些非常有帮助的说明!

编辑:这是我现在的代码,但我生成的总数也低于 10:

  let formation = [];
let total = 0;

for (let i = 0; i < 4; i ++) {
if (total < 9) {
formation[i] = Math.floor(Math.random() * 4) + 1;
} else {
formation[i] = 1;
}
}

最佳答案

您可以创建所有可能的组合并选择一个随机数组。

function get4() {

function iter(temp) {
return function (v) {
var t = temp.concat(v);
if (t.length === 4) {
if (t.reduce(add) === 10) {
result.push(t);
}
return;
}
values.forEach(iter(t));
};
}

const
add = (a, b) => a + b,
values = [1, 2, 3, 4],
result = [];

values.forEach(iter([]));
return result;
}

console.log(get4().map(a => a.join(' ')));
.as-console-wrapper { max-height: 100% !important; top: 0; }

一种在没有所有可能组合列表的情况下获取随机值的算法

它的工作原理是根据实际总和、索引、下一个索引所需的最小总和以及最大总和,使用随机值的一个因子和一个偏移量。

偏移量通常是最小总和,或者总和与最大总和之差的较大值。取因子取三个最小值乘以随机值。

The table illustrates all possible values of the sum and the needed iterations, based on a given value and the iteration for getting all values.

At the beginning the sum is the value for distribution in small parts. The result is the second block with a rest sum of 14 ... 10, because it is possible to take a value of 1 ... 5. The third round follows the same rules. At the end, the leftover sum is taken as offset for the value.


包含 1、...、5 值和 5 元素且总和为 15 的示例以及所有可能性:

min:     1
max: 5
length: 5
sum: 15

smin = (length - index - 1) * min
smax = (length - index - 1) * max
offset = Math.max(sum - smax, min)
random = 1 + Math.min(sum - offset, max - offset, sum - smin - min)

index sum sum min sum max random offset
------- ------- ------- ------- ------- -------
_ 0 15 4 20 5 1
1 14 3 15 5 1
1 13 3 15 5 1
1 12 3 15 5 1
1 11 3 15 5 1
_ 1 10 3 15 5 1
2 13 2 10 3 3
2 12 2 10 4 2
2 11 2 10 5 1
2 10 2 10 5 1
2 9 2 10 5 1
2 8 2 10 5 1
2 7 2 10 5 1
2 6 2 10 4 1
_ 2 5 2 10 3 1
3 10 1 5 1 5
3 9 1 5 2 4
3 8 1 5 3 3
3 7 1 5 4 2
3 6 1 5 5 1
3 5 1 5 4 1
3 4 1 5 3 1
3 3 1 5 2 1
_ 3 2 1 5 1 1
4 5 0 0 1 5
4 4 0 0 1 4
4 3 0 0 1 3
4 2 0 0 1 2
4 1 0 0 1 1

示例代码采用目标1, ..., 4,长度为4,总和为 10

function getRandom(min, max, length, sum) {
return Array.from(
{ length },
(_, i) => {
var smin = (length - i - 1) * min,
smax = (length - i - 1) * max,
offset = Math.max(sum - smax, min),
random = 1 + Math.min(sum - offset, max - offset, sum - smin - min),
value = Math.floor(Math.random() * random + offset);

sum -= value;
return value;
}
);
}

console.log(Array.from({ length: 10 }, _ => getRandom(1, 4, 4, 10).join(' ')));
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 将数字分成 4 个随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50405397/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com