I am trying to realize a certain mathematical combination into Javascript but can find the best way to do it.
What I am trying to achieve is finding the sum of combinations(consisting of 3 elements) out of N.
For example, how can I find sum of all possible combinations consisting of 3 elements out of 5?
Manually it looks like this:
Selections: A,B,C,D,E - all of them are numbers
All possible 3 out of 5 combos are as follows:
ABC ABD ABE ACD ACE ADE BCD BCE BDE CDE
ABC means A * B * C
The sum of combos in its simplified form will look like this:
AB(C+D+E) + AC(D+E) + ADE + BC(D+E) + BDE + CDE.
I have tried the following code but it did not work out:
function calc(arr) {
var total = 0;
for (let i = 0; i < arr.length; i++) {
let sum = 0;
for (let j = i + 1; j < arr.length; j++) {
sum += arr[j] + arr[j + 1] + arr[j + 2];
}
total += sum * arr[i] + arr[i + 1] + arr[i + 2];
}
return total;
}
var arr = [2, 3, 4, 5, 6];
console.log(calc(arr));