假设某Array
maxLength
项目长度太大
var maxLength = 3;
var arr = [1,2,3,4,5];
var tooBig = arr.length > maxLength;
是否存在通过组合项目值来缩短此数组长度的优化算法?
if(tooBig){
var newArr = refactor(arr, maxLength);
console.log(newArr); //[5,5,5]
}
尽可能均匀地重新分配非常重要:
//Could be reduced more evenly like above
console.log(newArr); //[1,6,8]
答案 0 :(得分:2)
基本思路是获取当前数组的总和。提取提醒,并在没有提醒的情况下获得平均值。然后创建一个新数组,只要提醒大于0,就用平均值+ 1填充它。
function refactor(arr, maxLength) {
var sum = arr.reduce(function(s, n) {
return s + n;
});
var remainder = sum % maxLength;
var average = (sum - remainder) / maxLength;
var arr = [];
for(var i = 0; i < maxLength; i++) {
arr.push(average + (i < remainder));
}
return arr;
}
var maxLength = 3;
var arr = [1,2,3,4,6];
var tooBig = arr.length > maxLength;
if(tooBig){
var newArr = refactor(arr, maxLength);
console.log(newArr); //[6,5,5]
}
如果您不需要数组项是整数,则可以直接获得平均值,并将其设置为每个数组项的值:
function refactor(arr, maxLength) {
var average = arr.reduce(function(s, n) {
return s + n;
}) / maxLength;
var arr = [];
for(var i = 0; i < maxLength; i++) {
arr.push(average);
}
return arr;
}
var maxLength = 3;
var arr = [1.7,2.4,3,4,6.934];
var tooBig = arr.length > maxLength;
if(tooBig){
var newArr = refactor(arr, maxLength);
console.log(newArr);
}