How to distribute 100 between number of items in an array

1.1k Views Asked by At

I am thinking of Round Robin algorithm but i am getting more confused.

Following is an example with only 4 items

items[]: [
"item1": 100,
"item2": 0,
"item3": 0,
"item4": 0,
]

Basically, I have to distribute 100 among 4 items. The total must always be 100, but each item must have round number can not have floating number.

items[]: [
"item1": 50,
"item2": 17,
"item3": 17,
"item4": 16,
]
items[]: [
"item1": 27,
"item2": 17,
"item3": 40,
"item4": 16,
]

If a new Item is added and assigned a value 10, The total exceed to 110, which gives us Excess of 10. The extra 10 must be taken from other items, 10 / 4 = 2.5, So we round up 2.5 to 3 and distribute it as follows:

items[]: [
"item1": 27, (27 - 3)
"item2": 17, (17 - 3)
"item3": 40, (40 - 3)
"item4": 16, (16 - 1)
"item5": 10,
]

So the result will be the following: the total must be 100

items[]: [
"item1": 24,
"item2": 14,
"item3": 37,
"item4": 15, 
"item5": 10,
]

Here is another example: where i increase 1 to 2nd item from last.

items[]: [
"item1": 24,
"item2": 14,
"item3": 37,
**"item4": 16,** 
"item5": 10,
]

The result 1 will be deducted from the first item:

items[]: [
"item1": 23,
"item2": 14,
"item3": 37,
"item4": 16,
"item5": 10,
]

I am not strong in JavaScript, if anyone can show me code examples I will be grateful, if this not enough please let me know, i will give more example

2

There are 2 best solutions below

3
Siva K V On

How about first make equal parts and add remainder value to one of item. (or something similar)

const items = (input, num = 4) => {
  const rem = input % num;
  const val = Math.floor(input / num);
  return Array.from({ length: num }, (_, i) => (!i ? (val + rem) : val));
};

console.log(items(101));
console.log(items(160));
console.log(items(25));

0
Malarivtan On

This is what I was looking for:

function* splitNParts(num, parts) {
    let sumParts = 0;
    for (let i = 0; i < parts - 1; i++) {
        const pn = Math.ceil(0.5 * (num - sumParts))
        yield pn
        sumParts += pn
    }
    yield num - sumParts;
}

console.log(...splitNParts(23, 2));