Allocate an array of integers proportionally compensating for rounding errors

后端 未结 5 712
暖寄归人
暖寄归人 2021-02-04 12:29

I have an array of non-negative values. I want to build an array of values who\'s sum is 20 so that they are proportional to the first array.

This would be an easy probl

5条回答
  •  旧巷少年郎
    2021-02-04 13:07

    You have set 3 incompatible requirements. An integer-valued array proportional to [1,1,1] cannot be made to sum to exactly 20. You must choose to break one of the "sum to exactly 20", "proportional to input", and "integer values" requirements.

    If you choose to break the requirement for integer values, then use floating point or rational numbers. If you choose to break the exact sum requirement, then you've already solved the problem. Choosing to break proportionality is a little trickier. One approach you might take is to figure out how far off your sum is, and then distribute corrections randomly through the output array. For example, if your input is:

    [1, 1, 1]
    

    then you could first make it sum as well as possible while still being proportional:

    [7, 7, 7]
    

    and since 20 - (7+7+7) = -1, choose one element to decrement at random:

    [7, 6, 7]
    

    If the error was 4, you would choose four elements to increment.

提交回复
热议问题