문제

I need to be able to edit weights values which are integers types by percentages.

For example: I got the following weights:

Var    Weight
x       100
y        50
z        50

So z is 25% ,y is 25% and x is 50%

Now if I want to be able to edit an existing weight or to add new weight by percentage input, how can I make sure that the weights will still be integers types and that I won't have any rounding needed.

For example, if I want to add a new weight which will be 25% from the total weights, how can I calculate this? Notice that I can change the other weights (increment/decrement) in order to achieve this.

But the necessary condition here that need to take place is that the weights will stay integers and the percentage of the new/edits weights will be as requested.

If I didn't have to make sure that the weights will be integers then it was easy, I can just use the following equation:

NewWeight = (Sum*RequestedPerecentage)/(1-RequestedPerecentage)

but that's not the case...

도움이 되었습니까?

해결책

Let's say you want to add a weight of w% to the list. In the case of your first example, w = 25.

First, find the total sum of the current weights.

x 100
y 50
z 50
----
Total 200

Multiply each current weight by (100-w).

x 7500
y 3750
z 3750

Multiply w by the total you previously found, and add it to the list.

x 7500
y 3750
z 3750
w 5000

You can reduce the numbers to their smallest form by dividing each one by the GCD of all the weights.

x 6
y 3
z 3
w 4

Watch out for overflow errors when using this method. It may be best to use some kind of bignum data type.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top