如何将数字尽可能均匀地分配到数组中?

我正在尝试将一个数字分配给一个数组。


例如,


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]


这看起来很容易,但我无法解决。有没有简单的方法可以解决这个问题?


ITMISS
浏览 82回答 1
1回答

慕村9548890

也许你正在寻找这样的东西:function getDistributedArray(n, max) {&nbsp; &nbsp; var a = [];&nbsp; &nbsp; var r = n; // rest of total sum&nbsp; &nbsp; var c = Math.ceil(n / max); // get maximal number of elements in array&nbsp; &nbsp; var i = 0; // index&nbsp; &nbsp; while (r > 0) {&nbsp; &nbsp; &nbsp; &nbsp; var t = Math.ceil(r / c); // get max number from the rest&nbsp; &nbsp; &nbsp; &nbsp; a[i++] = t;&nbsp; &nbsp; &nbsp; &nbsp; r -= t;&nbsp; &nbsp; &nbsp; &nbsp; c--;&nbsp; &nbsp; }&nbsp; &nbsp; 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]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript