I often need to divide quantities in recipes. Normally, this is straightforward: I have an array of items to divide and a total, so I can do something like public function divideAmounts(totalAmount:Number,coll:XMLListCollection):void {
var divisor:Number = coll.length;
var amtEach:Number = Math.round((totalAmount/divisor)/ .01) * .01;
trace("dividing "+totalAmount+" by "+divisor+" for an amount each of "+amtEach);
for (var i:int=0; i<divisor; i++) {
coll.@amount = amtEach;
}
} However, this time I have been handed a curve ball: some of the items have a maximum amount they can be. For example, item A has a maximum amount of .25, item B is maximum of 1, the other items have no limits. So if the total amount is 3, and I am dividing it by 3 items I can't simply set each one's amount to 1 (as I normally would, as the code above does). I need to set the amount of A to .25 so there is still the .75 "left over" that I now need to apply evenly to the remaining items. So that means the other 2 items B and C would be 1.375 each -- but, as I said above B also has a limit (of 1), so B would be 1 and C (no limits) would get the whole .75 remainder, and be 1.75. So A=.25, B= 1, C=1.75 for the total of 3. My question is, even conceptually, how would I approach a problem such as this in AS? I tried public function divideAmountsWithMaximums(totalAmount:Number,coll:XMLListCollection):void {
var divisor:Number = coll.length;
var amtEach:Number = Math.round((totalAmount/divisor)/ .01) * .01;
for (var i:int=0; i<divisor; i++) {
var max:Number = coll.@maxQty;
var amtToAdd:Number = (amtEach > max)? max :amtEach;
trace(coll.@sn+" has a max of "+coll.@maxQty+", adding "+amtToAdd);
coll.@qty = amtToAdd;
}
} Except that doesn't cascade in the proper order, "filling up" the smaller items first. Help and suggestions appreciated.
... View more