Reputation: 2421
I'm currently working with Google Apps Script and wish to distribute an array (eg. ['MP', 'JE', 'MC', 'GP', 'CZ', 'DM', 'MD']
) as evenly as possible against a number of spreadsheet rows.
Say there are 21 rows, and I'm using the above array of length 7
. I would want to iterate through each entry of the array and output each entry 3 times.
Seemingly simple enough to do:
var exampleArr = ['MP', 'JE', 'MC', 'GP', 'CZ', 'DM', 'MD'];
function distributeArr(arr, rowLen){
for (i = 0; n = arr.length, i < n; i++){
for (r = 0; r < rowLen / n; r++) {
console.log(arr[i]);
}
}
}
distributeArr(exampleArr, 21);
But when the two numbers aren't evenly divisible, it'll round up to the nearest match. What's a good way to deal with this while keeping the distribution of array items to rows as even as possible?
Upvotes: 1
Views: 1207
Reputation: 3298
One way is to get the remainder and distribute it to the staff.
function distributeArr(staffArr, numOfTasks) {
var numOfStaff = staffArr.length;
var extra = numOfTasks % numOfStaff;
var taskPerPerson = parseInt(numOfTasks / numOfStaff);
var assignment = staffArr.map(function(e) {
if (staffArr.indexOf(e) < extra) {
return [e, taskPerPerson + 1];
}
else {
return [e, taskPerPerson];
}
});
assignment.forEach(function(arr) {
// create arr[1] rows for staff arr[0]
});
}
var staffArr = ['MP', 'JE', 'MC'];
distributeArr(staffArr, 7); //assignment: [["MP", 3], ["JE", 2], ["MC", 2]]
distributeArr(staffArr, 6); //assignment: [["MP", 2], ["JE", 2], ["MC", 2]]
distributeArr(staffArr, 0); //assignment: [["MP", 0], ["JE", 0], ["MC", 0]]
distributeArr(staffArr, 1); //assignment: [["MP", 1], ["JE", 0], ["MC", 0]]
Upvotes: 3