[英]Evenly distribute a number of columns in x by a max amount per set
Is there an algorithm in javascript to evenly distribute a number of columns in X by a max amount of per set? javascript中是否有一种算法,可以按每组的最大数量均匀分配X中的列数?
For example, in the following scenarios: 例如,在以下情况下:
I would do it with these steps: 我将通过以下步骤进行操作:
Which should result in your desired, mostly evenly-split array. 这将导致您所需的,几乎是均匀分割的阵列。 Example:
例:
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.