I have a array like this:
const arr = [2, 3, 4, 12, 4, 55, 8, 16]
I want to get the sum of every five element of array's product. My current way is use five times for loop to calculate the result. It's holy shit! Is't have a elegant way to solve it?
The output should same as the below method:
function getSum(arr) {
let sum = 0
for (let i = 0; i < arr.length - 4; i++) {
for (let j = i + 1; j < arr.length - 3; j++) {
for (let k = j + 1; k < arr.length - 2; k++) {
for (let l = k + 1; l < arr.length - 1; l++) {
for (let m = l + 1; m < arr.length; m++) {
sum += arr[i] * arr[j] * arr[k] * arr[l] * arr[m]
}
}
}
}
}
return sum
}
Possible tuples for the above given example:
2 3 4 12 4
2 3 4 12 55
2 3 4 12 8
2 3 4 12 16
2 3 4 4 55
2 3 4 4 8
2 3 4 4 16
2 3 4 55 8
2 3 4 55 16
2 3 4 8 16
2 3 12 4 55
2 3 12 4 8
2 3 12 4 16
2 3 12 55 8
2 3 12 55 16
2 3 12 8 16
2 3 4 55 8
2 3 4 55 16
2 3 4 8 16
2 3 55 8 16
2 4 12 4 55
2 4 12 4 8
2 4 12 4 16
2 4 12 55 8
2 4 12 55 16
2 4 12 8 16
2 4 4 55 8
2 4 4 55 16
2 4 4 8 16
2 4 55 8 16
2 12 4 55 8
2 12 4 55 16
2 12 4 8 16
2 12 55 8 16
2 4 55 8 16
3 4 12 4 55
3 4 12 4 8
3 4 12 4 16
3 4 12 55 8
3 4 12 55 16
3 4 12 8 16
3 4 4 55 8
3 4 4 55 16
3 4 4 8 16
3 4 55 8 16
3 12 4 55 8
3 12 4 55 16
3 12 4 8 16
3 12 55 8 16
3 4 55 8 16
4 12 4 55 8
4 12 4 55 16
4 12 4 8 16
4 12 55 8 16
4 4 55 8 16
12 4 55 8 16