-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
28 lines (24 loc) · 812 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* Implementation of https://en.wikipedia.org/wiki/Greedy_number_partitioning
* Sorts the numbers in descending order
* Then iteratively add the next-largest number to a set in which the current sum is smallest.
* @param {number[]} array
* @param {number} numberOfSubsets
* @returns - Array of arrays of numbers
*/
function greedyPartitioning (array, numberOfSubsets) {
const sorted = array.sort((a, b) => b - a); // sort descending
const out = [...Array(numberOfSubsets)].map(x => {
return {
sum: 0,
elements: [],
};
});
for (const elem of sorted) {
const chosenSubset = out.sort((a, b) => a.sum - b.sum)[0];
chosenSubset.elements.push(elem);
chosenSubset.sum += elem;
}
return out.map(subset => subset.elements);
}
module.exports = greedyPartitioning