Javascript:子阵列的统一长度

时间:2014-05-13 15:57:52

标签: javascript arrays distribution content-length

我试图将数组拆分成块。块应该与函数指定的一样多。我已经拥有的是

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;
};

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

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

2 个答案:

答案 0 :(得分:4)

简单的数学。如果您有n项并希望将它们拆分为k个块,则每个块都将包含n / k个项目。但是如果n / k不是整数呢?然后,一些块将具有n / k rounded down项,一些将具有n / k rounded down + 1项。他们中有多少人拥有+ 1项? n % k

function distribute(a, k) { 

    var count = Math.floor(a.length / k); 
    var remain = a.length % k; 
    var result = []; 
    var index = 0; 

    for (var i = 0; i < k; i++) { 

        var number = count + (i < remain ? 1 : 0); 
        result.push(a.slice(index, index + number));
        index += number; 
    } 

    return result; 
}

distribute([1, 2, 3, 4, 5, 6, 7], 2);

--> [[1, 2, 3, 4], [5, 6, 7]]

Nordfjord编辑:更短,但与上述解决方案组合的值不同:

groupByNumberOfGroups = function(array, numberOfGroups){
    var groups = []
    for(var i = 0; i < numberOfGroups; ++i) groups.push([]);
    for(var i = 0; i < array.length; ++i) groups[i%numberOfGroups].push(array[i]);
    return groups;
}

答案 1 :(得分:0)

试试这个,

var groupByNumberOfGroups = function( array, NumberOfGroups ){
    var div = Math.floor( array.length / NumberOfGroups );
    var mod = array.length % NumberOfGroups;
    var result = [];

    var lowerBound=0, upperBound=0;
    for ( var k=0; k<NumberOfGroups; k++ ) {
        lowerBound = ( upperBound === 0 ) ? ( ( k < mod ) ? k * ( div + 1 ) : k * ( div ) ) : upperBound
        upperBound = ( k < mod ) ? ( lowerBound + div + 1 ) : ( lowerBound + div )
        result[ k ] = array.slice( lowerBound, upperBound );
    }
    return result;
};

groupByNumberOfGroups([1,2,3,4,5,6], 4); // [[1, 2], [3, 4], [5], [6]]
groupByNumberOfGroups([1,2,3,4,5,6,7,8,9,10,11,12,13,14], 8); // [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12], [13], [14]] 

js fiddle:link