1

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
Sandesh Gupta
  • 1,175
  • 2
  • 11
  • 19
Vic
  • 105
  • 1
  • 9

1 Answers1

0

You could use an iterative and recursive approach by checking the wanted length and by calling the function again with ither the element at the index or without.

function getCombinations(list, size) {

    function fork(index, values) {
        if (values.length === size) {
            result.push(values);
            return;
        }
        if (index >= list.length) {
            return;
        }
        fork(index + 1, values.concat(list[index]));
        fork(index + 1, values);
    }

    var result = [];
    fork(0, []);
    return result;
}

var result = getCombinations([2, 3, 4, 12, 4, 55, 8, 16], 5),
    sum = result.reduce((s, a) => s + a.reduce((a, b) => a * b), 0);

console.log(sum);                          // 2927456
console.log(result.length);                //      56
console.log(result.map(a => a.join(' ')));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392