简体   繁体   English

将数组的内容均匀分布到多行

[英]Evenly distribute contents of array to a number of rows

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.我目前正在使用 Google Apps Script 并希望均匀分布一个数组(例如['MP', 'JE', 'MC', 'GP', 'CZ', 'DM', 'MD'] )尽可能针对多个电子表格行。

Say there are 21 rows, and I'm using the above array of length 7 .假设有 21 行,我正在使用上述长度为7数组。 I would want to iterate through each entry of the array and output each entry 3 times.我想遍历数组的每个条目并输出每个条目 3 次。

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?在保持数组项到行的分布尽可能均匀的同时处理这个问题的好方法是什么?

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]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM