js实现平均分配

新手上路,请多包涵

需求是这样的:
这里有20个任务需要将其平均分配给6个人员,现在点击平均分配按钮实现的效果如下图所示

clipboard.png
希望实现的效果:将多余的两条分给最开始人员

clipboard.png
已有代码如下

    countAvgNum() {
      if (this.distribute == null || this.distribute.length == 0) {
        this.$message.warning("请添加分配对象");
        return;
      }
      // 防止缓存不变
      this.distribute.forEach(item => {
        item.disNum = 0;
      });
      let total = this.remainNum,
        dataLength = this.distribute.length;
      //当分配的数量大于总数的时候
      if (total < dataLength) {
        // 前面几个都是1,后面的是0
        var num = total;
        this.distribute.forEach(item => {
          if (num > 0) {
            item.disNum = 1;
            num--;
          } else {
            item.disNum = 0;
          }
        });
      } else {
        this.avgNum = parseInt(total / dataLength)
          ? parseInt(total / dataLength)
          : 0;
        this.distribute = this.distribute.map(value => {
          value.disNum = this.avgNum;
          return value;
        });
        // this.distribute[dataLength - 1].disNum =
        //   total - this.avgNum * (dataLength - 1);
      }
    },
阅读 9.6k
4 个回答
let total = 20, count = 6;

let base = Math.floor(total / count);
let rest = total % count;

arr = [];
for(let i=0; i<count; i++)
{
    arr.push(base + (i<rest?1:0))
}
console.log(arr)

不是直接用余数就行吗,简单敲了一下

function getAvargeTask(num, people) {
    let firstNum = Math.floor(num / people);
    let restNum = num - firstNum * people;
    return new Array(people).fill(firstNum).map((val,index) => {
        if(index < restNum) {
            return val + 1
            } else {
            return val
        }
    })
}

对于非负整数来说,更高效的是:

function getA(num, pnum){ // 正常情况下,返回有pnum个元素的数组,每个元素是对应任务数
    if(num<0 || pnum<=0) return []; // 返回为空数组表示输入数据有错
    let y=num%pnum;
    let b = (num-y)/pnum;
    var rt=[];
    let i=0;
    while(i<pnum){
        let t=b;
        if(i<y) t++;
        rt.push(t);
    }
    return rt;   
}
function average(t, c) {
    var l = [], a = t / c | 0, b = t % c, i = -1;
    while (++i < c) l[i] = +(i < b) + a;
    return l;
}
console.log(average(20, 6));
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题