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 ]
热门推荐
2 年月日祝福语简短
10 中秋妈妈生日祝福语简短
11 对儿子祝福语简短精辟
12 新年祝福语简短聪明可爱
13 生日聚会祝福语简短的
14 生日祝福语大全女生简短
15 分别祝福语简短情侣短句
16 周末思念祝福语大全简短
17 微信晚上祝福语简短
18 春节后的祝福语简短