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 婆婆高寿祝福语大全简短