如果数组无法均匀划分,我想将数组分成几组,最后几组的大小最大。就像2024年欧洲杯预选赛一样,有53支球队分为10个小组,最后几组的规模最大(5x5x5x5x5x5x5x6x6x6)。这是对数组进行分块的代码,但它具有最大尺寸的前几组 [Fiddle](6x6x6x5x5x5x5x5x5x5):
function partition(arr: Team[], group: number) {
let rest = arr.length % group;
let size = Math.floor(arr.length / group);
let j = 0;
return Array.from({ length: group }, (_, i) => {
return arr.slice(j, (j += size + (i < rest ? 1 : 0)));
});
}
let data = Array.from({length: 53}, (_,i) => i+1);
let result = partition(data, 10);
// result.reverse() is not ideal and would complicate things.
console.log(result);
用
reverse()
来翻转结果在我的情况下并不理想,因为 arr
中的一些队伍一定是前几组。如果使用reverse
,这些球队将被安排在最后几组。有没有办法将数组分成这样的东西(5x5x5x5x5x5x5x6x6x6)?
尝试以下操作将额外的成员添加到组的末尾
function partition(arr, group) {
const totalLength = arr.length;
const size = Math.floor(totalLength / group);
const largerGroupCount = totalLength % group; // find how many groups are large
const groups = [];
let startIndex = 0;
for (let i = 0; i < group; i++) {
const currentGroupSize = size + (i >= group - largerGroupCount ? 1 : 0);
groups.push(arr.slice(startIndex, startIndex + currentGroupSize));
// update the index for the next group
startIndex += currentGroupSize;
}
return groups;
}
let data = Array.from({length: 53}, (_, i) => i + 1);
let result = partition(data, 10);
console.log(result);