Skip to content

Instantly share code, notes, and snippets.

@Richienb
Last active November 9, 2021 10:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Richienb/3ba40120ba96adbb1520cac2536553d5 to your computer and use it in GitHub Desktop.
Save Richienb/3ba40120ba96adbb1520cac2536553d5 to your computer and use it in GitHub Desktop.
function split(array, groups = 2) {
array = array.sort((a, b) => b - a);
const parts = Array.from({length: groups}, () => []);
const partLengths = Array.from({length: groups}, () => 0);
for (const item of array) {
const partIndex = partLengths.indexOf(Math.min(...partLengths));
parts[partIndex].push(item);
partLengths[partIndex] += item;
}
return parts;
}
function split(array) {
array = array.sort((a, b) => b - a);
const a = [];
let aSum = 0;
const b = [];
let bSum = 0;
for (const item of array) {
if (aSum < bSum) {
a.push(item);
aSum += item;
} else {
b.push(item);
bSum += item;
}
}
return [a, b];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment