gpt4 book ai didi

javascript - 将数字数组缩减为固定长度的较小数字数组

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:51:52 25 4
gpt4 key购买 nike

假设我有一个数组,它的项目长度太大对于某些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]

最佳答案

基本思路是获取当前数组的总和。提取提醒,并在没有提醒的情况下得到平均值。然后新建一个数组,只要reminder大于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);
}

关于javascript - 将数字数组缩减为固定长度的较小数字数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48309803/

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