CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate: Re: [lightspd] distributed amounts: Edit Log



Kenosis
User

Mar 15, 2013, 4:11 PM


Views: 922
Re: [lightspd] distributed amounts

Perhaps the following will be helpful:

Code
use strict; 
use warnings;

my @AOH = (
{
plu => "coke",
amt => "299",
discAmt => "299",
void => "f",
},
{
plu => "pepsi",
amt => "199",
discAmt => "199",
void => "f",
},

);

@AOH = sort { $a->{'amt'} <=> $b->{'amt'} } @AOH;
my $discount = 400;
my $numItems = @AOH;

for my $item (@AOH) {
my $finalDiscount =
$discount / $numItems <= $item->{amt}
? $discount / $numItems
: $item->{amt};

$discount -= $finalDiscount;
$numItems--;

print 'Item: '
. $item->{plu}
. "\t Amt: "
. $item->{amt}
. "\tDiscount: "
. $finalDiscount . "\n"

}


Output:

Code
Item: pepsi	 Amt: 199	Discount: 199 
Item: coke Amt: 299 Discount: 201


It first sorts the hash refs from lowest to highest amt. In the for loop, the ternary operator checks whether dividing the total discount amount evenly may exceed the item cost. If it does, the item cost is the discount amount, else the total discount left divided by the number of items left is used.

Tested OK using three items...

Edit: Changed

Code
{ $a->{'discAmt'} <=> $b->{'discAmt'} }


to

Code
{ $a->{'amt'} <=> $b->{'amt'} }



(This post was edited by Kenosis on Mar 15, 2013, 5:04 PM)


Edit Log:
Post edited by Kenosis (User) on Mar 15, 2013, 4:12 PM
Post edited by Kenosis (User) on Mar 15, 2013, 4:13 PM
Post edited by Kenosis (User) on Mar 15, 2013, 4:59 PM
Post edited by Kenosis (User) on Mar 15, 2013, 5:04 PM


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives