我想生成一个包含6个元素的数组,总和始终为N。只有正整数。
var arr = generateArray();
arr.length === 6; //always true
arr.reduce((a,b) => a + b) === 16; //also always true
基本上是一种更优雅的执行方式:
rndInt = (max) => Math.floor(Math.random() * Math.floor(max)),
rndAssign = (piles, items) => {
let groups = new Int8Array(piles);
for (i = 0; i < items; i++) {
groups[rndInt(piles)]++
}
return groups
},
答案 0 :(得分:0)
您可以尝试以下操作:
const generateArray = (sum = 16, groupsQty = 6) => {
this.currentSum = 0;
// create empty array of given length and populate it with items in sum not exceeding given sum
return Array.from({length: groupsQty}).reduce((res, curr, ind) => {
const item = ind === groupsQty - 1 ? sum - this.currentSum : Math.floor(Math.random() * (sum + 1 - this.currentSum));
// store current sum
this.currentSum += item;
return [
...res,
item
]
}, [])
};
const arr = generateArray();
console.log(arr);
console.log('LENGTH:', arr.length);
console.log('SUM:', arr.reduce((a, b) => a + b, 0));
答案 1 :(得分:0)
您可以使用带有值的数组
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
或[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
,取决于您是否也想要零,并使用brte force方法通过取六个元素来获得总和为16
的值的任何可能组合。
为进一步选择,您可以选择一个随机数组。此随机值呈正态分布。
结果可能需要更长的时间才能运行。
function get6(values) {
function iter(temp) {
return function (v) {
var t = temp.concat(v);
if (t.length === 6) {
if (t.reduce(add) === 16) {
result.push(t);
}
return;
}
values.forEach(iter(t));
};
}
const
add = (a, b) => a + b,
result = [];
values.forEach(iter([]));
return result;
}
var small = get6([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]),
big = get6([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]);
console.log(small.length); // 3003
console.log(small.map(a => a.join(' ')));
console.log(big.length); // 20349
console.log(big.map(a => a.join(' ')));
.as-console-wrapper { max-height: 100% !important; top: 0; }