Reputation: 1776
I need to write a function to calculate the fictitious value of some selected items in a website.
These are the only 4 discounts that will exist but they can be accumulative, so if the user selected 110 (80+24+6) the value should be (50+20+6). Let's see some other examples:
I hope I explained myself. I can guess I need to use mod logical operator but I have no idea on how to start writing this algorithm and I think I need a little help.
Upvotes: 2
Views: 128
Reputation: 829
Javascript is not my usual programming language, but something like this should work.
The idea is to apply each time the best discount. To know how many times you can apply a discount you just need to take the quotient of the division between the remaining bought items and the items needed to apply the discount, i.e. if you have 17 items and need to apply a discount of 8, 17/8 = 2 and there would be 1 remaining item. Then, once you know how many times you apply the discount, subtract the items and keep going.
function calculate_price(total_items) {
var needed = [1, 8, 24, 40, 80];
var price = [1, 7, 20, 30, 50];
var total = 0;
for (var i = needed.length - 1; i >= 0; --i) {
var qtt = Math.floor(total_items/needed[i]);
total_items -= qtt*needed[i];
total += qtt*price[i];
}
return total;
}
Upvotes: 2
Reputation: 2916
Here is some pseudo-code to get you started:
remainder = initial value
total = 0
array of discount objects ordered descending by discount i.e. [{ level: 80, amount: 50 }, { level: 40, amount: 30 }, etc.]
loop over array doing the following calculation:
get total number of discounts to apply at this level (divide remainder by current level and round down)
add total number of discounts times the current level's amount to the total value
set remainder to what's left (current remainder mod current level)
add the remainder after the loop has run to the total calculated so far
Upvotes: 0