我正在尝试将数字分配给数组。
例如,
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]
这似乎很简单,但我无法解决。有没有简单的方法可以解决这个问题?
答案 0 :(得分:3)
可能您正在寻找这样的东西:
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]