I have an array of non-negative values. I want to build an array of values whose sum is 20, so that they are proportional to the first array.
This would be an easy problem, except that I want the proportional array to sum exactly 20, compensating for any rounding error.
For example, an array
input = [400, 400, 0, 0, 100, 50, 50]
will give
output = [8, 8, 0, 0, 2, 1, 1]
sum(output) = 20
However, in most cases there will be many rounding errors, for example
input = [3, 3, 3, 3, 3, 3, 18]
naively gives
output = [1, 1, 1, 1, 1, 1, 10]
sum(output) = 16 (ouch)
Is there a good way to distribute the output array so that it adds up to 20 each time?