gpt4 book ai didi

Javascript:子数组的统一长度

转载 作者:行者123 更新时间:2023-11-30 10:16:01 24 4
gpt4 key购买 nike

<分区>

我正在尝试将数组拆分为多个 block 。 block 应该与函数指定的一样多。我已经拥有的是

groupBySize = function(array, groupSize){
if(groupSize === 0){
return;
}
var groups = [];
var i,j,temparray;
for (i=0,j=array.length; i<j; i+=groupSize) {
temparray = array.slice(i,i+groupSize);
groups.push(temparray);
}
return groups;
};
groupByNumberOfGroups = function(array, NumberOfGroups){
var groupSize = Math.floor(array.length/NumberOfGroups);
var groups = this.groupBySize(array, groupSize);
// Let's make sure we get the right amount of groups
while(groups.length > NumberOfGroups){
console.log(groups.length + ">" + NumberOfGroups);
var last = groups[(groups.length-1)];
for(var j = 0; j< last.length; j++){
var temp = j;
while(groups[temp].length > groups[temp+1]){
temp++;
}
groups[j].push(last[j]);
}
groups.pop();
}
return groups;
};

这成功地将数组拆分为正确数量的 block 。我希望它能使每个 block 的长度尽可能统一,所以如果我将像 [1,2,3,4,5,6] 这样的数组分成 4 个 block ,我会得到 [[1,2 ],[3,4],[5],[6]]。有什么建议吗?

缺点的另一个例子:将 [1,2,3,4,5,6,7,8,9,10,11,12,13,14] 分成 8 个 block 得到 [[1,2,3 ,4,5,6,7],[8],[9],[10],[11],[12],[13],[14]]

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com