JavaScript 中陣列的全部和組合
我們需要編寫一個 JavaScript 函式,該函式以一個數字陣列作為第一個引數和一個數字(稱為 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 ]
廣告