在x中均匀分配多个列,每组最大量

时间:2018-03-13 20:08:17

标签: javascript

javascript中是否有一个算法可以按X的最大数量均匀分配X中的多个列?

例如,在以下场景中:

  • 列数为11。
  • 每组最大数量5.
  • 答案是4,4,3
  • 列数为12
  • 每组最大数量为5
  • 答案是4,4,4
  • 列数为15
  • 每组最大数量为5
  • 答案是5,5,5
  • 列数为13
  • 每组最大数量为5
  • 答案是5,4,4

1 个答案:

答案 0 :(得分:1)

我会按照以下步骤进行:

  • 计算最终数组的项目数。
  • 创建该长度的数组,每个条目都是最大数字。这可能会溢出列数,但是:
  • 遍历该数组,从每个值中减去1,直到我们达到所需的列数。

哪个应该会产生你想要的,大多数均匀分裂的数组。例如:



function makeEvenSpread(numCol, maxNum) {
    // Length of final array. This is fixed so we can calculate it up front.
    const len = Math.ceil(numCol/maxNum);
    
    // An array of that length, filled with the maxNum. Probably this overflows
    // the numColumns constraint, which we fix in the next step.
    const overflowed = new Array(len).fill(maxNum);
    
    // This is how much the overflowed array's sum exceeds numCol.
    let over = len*maxNum - numCol;
    
    // Now you need to go through the array and subtract one from each element
    // in turn, until we hit the desired sum. If we get to the end of the array,
    // start again from the beginning.
    let ind = 0;
    while (over--) {
        overflowed[ind++%len]--;
    }
    
    // You want the smaller numbers at the end, so reverse the result.
    return overflowed.reverse();
}

console.log(makeEvenSpread(11, 5)) // [4, 4, 3]
console.log(makeEvenSpread(12, 5)) // [4, 4, 4]
console.log(makeEvenSpread(15, 5)) // [5, 5, 5]
console.log(makeEvenSpread(13, 5)) // [5, 4, 4]