
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
Can Array be Divided into N Partitions with Equal Sums in JavaScript
We are required to write a JavaScript function that takes in an array of numbers, arr, as the first argument and a number, num, as the second argument.
The function should determine whether there exists a way of distributing the elements of the array arr into num groups such that all the groups have equal sum. If there exists any such way, our function should return true, false otherwise.
For example −
If the input array and the number are −
const arr = [4, 6, 3, 3, 7, 4, 1]; const num = 4;
Then the output should be −
const output = true;
because the four groups are: [7], [1, 6], [4, 3], [4, 3]
Example
The code for this will be −
const arr = [4, 6, 3, 3, 7, 4, 1]; const num = 4; const canDivide = (arr = [], num = 1) => { const sum = arr.reduce((acc, num) => acc + num); if (sum % num !== 0 || arr.some(num => num > sum / num)) { return false; } const used = new Set(); return (function find(start, target) { if (used.size === arr.length) { return true; } if (target < 0) { return false; } if (target === 0) { return find(0, sum / num); } for (let i = start; i < arr.length; i++) { if (!used.has(i)) { used.add(i); if (find(i + 1, target - arr[i])) { return true; } used.delete(i); } } return false; })(0, sum / num); }; console.log(canDivide(arr,num));
The steps we took in our solution are −
Step 1. If total sum cannot be divided by num or one of the number is greater than sum/num, we return false.
Step 2.We used a HashSet to track used numbers.
Step 3. We started finding the sub partitions.
If all the numbers are used, we are done.
If the subset sum was too large, we stopped searching.
If we have found one subset, we continued the search till we use all the numbers.
And lastly, we tried every unused number.
Output
And the output in the console will be −
true