我正在尝试将一个数字分配给一个数组。例如,const num = 30;const maxNumPerElement = 10;const arr = getDistributedArray(num, maxNumPerElement);console.log(arr);结果应该是[10, 10, 10]另一个例子,const num = 32;const maxNumPerElement = 10;const arr = getDistributedArray(num, maxNumPerElement);console.log(arr);结果应该是[8, 8, 8, 8]最后一个例子,const num = 34;const maxNumPerElement = 10;const arr = getDistributedArray(num, maxNumPerElement);console.log(arr);结果应该是[9, 9, 8, 8]这是我的代码,只能工作到 98。如果达到 99,它就不再工作,我不知道为什么。 const num = 99; const maxNumPerElement = 10; if (num > maxNumPerElement) { const numSubtitles = Math.ceil(num / maxNumPerElement); const minNumPerElement = Math.floor(num / numSubtitles); const numArray = new Array(numSubtitles).fill(minNumPerElement); const remainder = num % minNumPerElement; for (let i = 0; i < remainder; i++) { numArray[i]++; } const sum = numArray.reduce(function (a, b) { return a + b; }, 0); if (sum !== num) { console.log("ERROR!!", num, numArray); } else { console.log(num, numArray); } }结果:ERROR!! 99 [9, 9, 9, 9, 9, 9, 9, 9, 9, 9]这看起来很容易,但我无法解决。有没有简单的方法可以解决这个问题?
1 回答
慕村9548890
TA贡献1884条经验 获得超4个赞
也许你正在寻找这样的东西:
function getDistributedArray(n, max) {
var a = [];
var r = n; // rest of total sum
var c = Math.ceil(n / max); // get maximal number of elements in array
var i = 0; // index
while (r > 0) {
var t = Math.ceil(r / c); // get max number from the rest
a[i++] = t;
r -= t;
c--;
}
return a;
}
console.log(getDistributedArray(30, 10)); // [10, 10, 10]
console.log(getDistributedArray(32, 10)); // [8, 8, 8, 8]
console.log(getDistributedArray(34, 10)); // [9, 9, 8, 8]
console.log(getDistributedArray(99, 10)); // [10, 10,..., 9]
添加回答
举报
0/150
提交
取消