Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding all possible combined (plus and minus) sums of n arguments JavaScript
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
Advertisements