distribute items into containers evenly without splitting

686 Views Asked by At

Im trying to figure out how to place a number of items into containers evenly but without splitting.

Easy example:

11 items, 2 containers

11/2 = 5.5

so even distribution would look like this (without splitting):

container 1 = 5 items

container 2 = 6 items

but of course as the numbers grow and divisions results in decimals its gets a bit more complicated

111 items, 4 containers

111/4 = 27.75

In this case how do i turn .75 into an even distribution?

what equation would be give me 3? the number of extra items that will need to be distributed to a different container?

container 1 = 27 items

container 2 = 28 items

container 3 = 28 items

container 4 = 28 items

1

There are 1 best solutions below

0
On BEST ANSWER

Let's say you have $n$ items and $c$ containers. You can safely put $\lfloor n/c \rfloor$ items into each container, where $\lfloor x \rfloor$ is the floor of $x$, i.e., $x$ rounded down to an integer.

Therefore the number of remaining items to be distributed is $$n - c\left\lfloor \frac nc \right\rfloor.$$

In the example you gave, this would be $$111 - 4\left\lfloor \frac {111}4 \right\rfloor = 111 - 4(27) = 3.$$

Note that if $c$ divides $n$, then $\lfloor n/c \rfloor = n/c$, so the formula reduces to $$n - c\lfloor n/c \rfloor = n - c(n/c) = n - n = 0,$$ as expected.