Zack Lee
Zack Lee

Reputation: 3044

How to distribute a number to an array as evenly as possible?

I'm trying to distribute a number to an array.

For example,

const num = 30;
const maxNumPerElement = 10;
const arr = getDistributedArray(num, maxNumPerElement);
console.log(arr);

The result should be [10, 10, 10]

Another example,

const num = 32;
const maxNumPerElement = 10;
const arr = getDistributedArray(num, maxNumPerElement);
console.log(arr);

The result should be [8, 8, 8, 8]

Last example,

const num = 34;
const maxNumPerElement = 10;
const arr = getDistributedArray(num, maxNumPerElement);
console.log(arr);

The result should be [9, 9, 8, 8]

And here's my code that works only until 98. If it reaches 99, it no longer works and I don't know why.

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

Result: ERROR!! 99 [9, 9, 9, 9, 9, 9, 9, 9, 9, 9]

It seemed easy but I can't solve it. Is there an easy way to solve this?

Upvotes: 1

Views: 775

Answers (1)

Iłya Bursov
Iłya Bursov

Reputation: 24146

probably you're looking for something like this:

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]

Upvotes: 4

Related Questions