简体   繁体   English

按每组最大数量均匀分配x中的列数

[英]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: 例如,在以下情况下:


  • Number of columns is 11. 列数为11。
  • Max number per set 5. 每套最大数量5。
  • Answer would be 4,4,3 答案将是4,4,3

  • Number of columns is 12 列数为12
  • Max number per set is 5 每套最大数量为5
  • Answer would be 4, 4, 4 答案是4、4​​、4

  • Number of Columns is 15 列数为15
  • Max number per set is 5 每套最大数量为5
  • Answer would be 5, 5, 5 答案是5、5、5

  • Number of Columns is 13 列数是13
  • Max number per set is 5 每套最大数量为5
  • Answer would be 5,4,4 答案将是5,4,4

I would do it with these steps: 我将通过以下步骤进行操作:

  • Calculate how many items the final array will have. 计算最终数组将包含多少项。
  • Create an array of that length, with every entry as the max number. 创建一个具有该长度的数组,每个条目为最大数量。 This probably overflows the number of columns, but: 这可能会使列数溢出,但是:
  • Iterate through that array, subtracting 1 from each value until we are at the desired number of columns. 遍历该数组,从每个值中减去1,直到达到所需的列数为止。

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.

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