Add and Remove percentage proportionally

Asked

Viewed 276 times

3

Doubt is in mathematics, a calculation that will be used in a program.

Let’s assume I have 3 items with different percentages:

Item 1 - 10%
Item 2 - 40%
Item 3 - 50%

I want to remove for example 10% of Item 3 and distribute this percentage in the other two proportionally, generating the following result:

Item 1 - 12%
Item 2 - 48%
Item 3 - 40%

Does anyone have any idea of the calculation or how I get the result?

  • In what programming language will do this?

  • I will do in javascript

  • There are always 3 items, and the distribution is always from the third to the other two?

  • There is no order @bfavaretto, I can remove or add any item, and the added/removed amount I have to redistribute proportionally

1 answer

2

Test like this:

var items = {
    item1: 10,
    item2: 40,
    item3: 50
};

function distribuir(el, qtd) {

    var somaTotal = 0,
        nrItems = 0;
    for (var este in items) {
        if (items[el] != items[este]) {
            somaTotal += items[este];
            nrItems++;
        }

    }

    for (var este in items) {
        if (items[el] != items[este]) {
            if (somaTotal == 0) items[este] += qtd / nrItems;
            else items[este] += (items[este] || 1) * qtd / somaTotal;
        } else items[este] -= qtd;
    }
    return items;
}
distribuir('item3', 10); // dá Object {item1: 12, item2: 48, item3: 40} 

Example

  • Hello Sergio, thank you very much. Just gave a problem with the inputs: 100, 0, 0. How I can handle when the value is 0?

  • @user4919, like this? the items have value 100, 0 and 0? and remove % from whom?

  • Ai removes 10% of Item 1 (100) for example.

  • @user4919, you are right. I have now corrected my answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.