tags:

views:

159

answers:

2

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  A: 

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
Amber
Really appreciate your help. I implemented your suggestion. But I think I'm off still...
CrashRoX
See comment above.
Amber
A: 

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;
}
Daniel Ice
I appreciate your contribution. It's not exactly what I was looking for. Yours takes a cut at each level. The solution from Dav accounts for previous tiers. Thanks again.
CrashRoX