Finding all possible combined (plus and minus) sums of n arguments JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that in any number of arguments (all of Number type).

The function should calculate all possible sums of addition and subtraction.

For example − If the arguments are 1, 2, 3

Then all possible combinations are −

1 + 2 + 3
1 - 2 - 3
1 + 2 - 3
1 - 2 + 3

Finally, the function should the sum that is closest to 0. In this case, that answer would just be 0.

Example

const findSmallestPositive = (...arr) => {
   let set = new Set([Math.abs(arr[0])]);
   for (let i = 1;
   i < arr.length; i++){
      const secondSet = new Set;
      for (let d of Array.from(set)){
         secondSet.add(Math.abs(d + arr[i]))
         secondSet.add(Math.abs(d - arr[i]))
      };
      set = secondSet;
   };
   return Math.min(...Array.from(set))
};
console.log(findSmallestPositive(5,3))
console.log(findSmallestPositive(1,2,3))
console.log(findSmallestPositive(1,2,3,5))

Output

This will produce the following output −

2
0
1
raja
Published on 25-Nov-2020 09:22:25
Advertisements