Calculating revenue share at different tiers

烂漫一生 提交于 2019-12-24 19:24:28

问题


I'm trying to write a function that can calculate revenue at different tiered levels... For example you sell $10000 worth of widgets. Any earnings from $1 - $999 we take 50%, $1000 - $4999 we take 25%, $5000 - $9999 we take 10%, $10000 - $19999 5%.

The percentage is not taken based on the final value. So if you earned $10000 you don't just fall into the 10% column. Your first $1000 is subject to 50%, the next $5000 25%, the next $4000 10%.

Thanks in advance.

**Final working code. Thanks for the help!

    $input = 10000;

    $tiers = array('1000' => .5, '5000' => .25, '10000' => .1, '20000' => .05, '22000' => .01);

    $accounted_for = 0;
    $total_share = 0;

    $tier = each($tiers);
    while($accounted_for < $input) {

        $cutoff = $tier[0];
        $percent = $tier[1];

        $level = (min($cutoff, $input) - $accounted_for) * $percent;

        $total_share += $level;

        $accounted_for = $cutoff;

        $tier = each($tiers);
    }

    return $total_share;

回答1:


Since you haven't specified a language, here's some pseudocode:

input = 99999

tiers = [list of (%,cutoff) tuples]

accounted_for = 0
total_share = 0

while accounted_for is less than input:
    percent,cutoff = next element of tiers
    total_share += (min(cutoff,input) - accounted_for) * percent
    accounted_for = cutoff

return total_share



回答2:


What you are doing is how the IRS tax code works, except the IRS gets more the more you make. In this model the commission slides down the more you sell. I am assuming you want the answer in PHP since you put it in the PHP category. If you wanted to have different schedules for different sales people you could make the tiers array an argument for the function.

function calculateEarnings($grossAmountSold) {
    $earnings = 0;
    $accountedFor = 0;
    $tiers = array('1000' => .5, '5000' => .25, '10000' => .1, '20000' => .05, '22000' => .01);

    while($accountedFor < $grossAmountSold) {
        list($cutoff, $commissionRate) = each($tiers);
        if($grossAmountSold < $cutoff) {
            $sold = $grossAmountSold - $accountedFor;
        } else {
            $sold = $cutoff - $accountedFor;
        }
        $earnings += $sold * $commissionRate;
        $accountedFor += $cutoff;
    }
    return $earnings;
}


来源:https://stackoverflow.com/questions/1817920/calculating-revenue-share-at-different-tiers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!