需求
生成一个指定长度为 count
的数组,数组元素下限为 min
,数组元素上限为 max
,要求所有数组元素之和为 sum
,且数组元素具有随机性(即元素值波动性较大)。
示例:
输入:{sum: 5000, min: 180, max: 250, count: 25}
输出:[181, 183, 184, 184, 188, 191, 193, 200, 184, 185, 233, 216, 186, 206, 182, 180, 230, 222, 211, 191, 223, 215, 181, 233, 218]
解法
function getArr(params) {
const arr = Array.from({length: params.count}, () => Math.floor(Math.random() * (params.max - params.min + 1)) + params.min);
let sum = arr.reduce((prev, curr) => prev + curr, 0);
let diff = params.sum - sum;
while (diff !== 0) {
const randomDiff = Math.floor(Math.random() * diff);
let index = arr.findIndex((item) => item + randomDiff < params.max && item + randomDiff > params.min);
if (index >= 0) {
arr[index] += randomDiff;
diff = diff - randomDiff;
}
}
return arr;
}
测试:
getArr({sum: 5000, min: 180, max: 250, count: 25})
// [181, 181, 186, 196, 199, 186, 190, 190, 186, 184, 211, 185, 185, 189, 227, 233, 208, 220, 216, 213, 196, 238, 187, 230, 183]