javascript中是否有一个算法可以按X的最大数量均匀分配X中的多个列?
例如,在以下场景中:
答案 0 :(得分: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]