JavaScript中数组总和的所有组合
我们需要编写一个JavaScript函数,该函数将Numbers数组作为第一个参数,并将数字(例如n)作为第二个参数。数字n将始终小于或等于数组的长度。
我们的函数应该从原始数组中返回长度为n的所有可能子数组的所有元素之和的数组。
例如,如果输入为-
const arr = [2, 6, 4]; const n = 2;
那么输出应该是-
const output = [8, 10, 6];
示例
为此的代码将是-
const arr = [2, 6, 4];
const n = 2;
const buildCombinations = (arr, num) => {
const res = [];
let temp, i, j, max = 1 << arr.length;
for(i = 0; i < max; i++){
temp = [];
for(j = 0; j < arr.length; j++){
if (i & 1 << j){
temp.push(arr[j]);
};
};
if(temp.length === num){
res.push(temp.reduce(function (a, b) { return a + b; }));
};
};
return res;
}
console.log(buildCombinations(arr, n));输出结果
控制台中的输出-
[ 8, 6, 10 ]
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语