-1

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...

Tomer Peled
  • 3,571
  • 5
  • 35
  • 57
  • 1
    You can display the values in truncated form but hold the values in code as floats, simply cast the value to int when displaying the value like so, in c#: `var xValue = (int)x;` – Mr. Mr. Feb 19 '13 at 14:40
  • Yes but with this approach eventually I will lose precision... – Tomer Peled Feb 19 '13 at 14:45
  • 1
    "Notice I can change the other weights in order to achieve this". Is there any particular constraint on how you can change the weights? If not, the problem is easy. If you are trying to add a weight of X% to the list, decrement all weights but the first one to 0, and increment/decrement the first weight to (100-X). Taking your first example, the result is x=75, y=0, z=0, new_value=25. – Kevin Feb 19 '13 at 14:49
  • The other weights should be "suffer" form the new weight equally as much as possible - so making them 0 is not good... – Tomer Peled Feb 19 '13 at 14:58
  • @Kevin did not mean the other weight is zero, he means that they should START at zero and you increase each by one unit until ALL units have been applied. – Mr. Mr. Feb 19 '13 at 15:42
  • Seems like a math question to me... – Peter Ritchie Feb 19 '13 at 15:47

1 Answers1

2

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.

Kevin
  • 74,910
  • 12
  • 133
  • 166
  • Thanks! that's the answer I was looking for - I just figure this and then saw you answered over here. Thanks again!!! – Tomer Peled Feb 19 '13 at 16:28