代码之家  ›  专栏  ›  技术社区  ›  Zack Lee

如何将一个数尽可能均匀地分配给数组?

  •  0
  • Zack Lee  · 技术社区  · 4 年前

    我试图把一个数分配给一个数组。

    例如,

    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 回复  |  直到 4 年前
        1
  •  3
  •   mplungjan Gvidas    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]