2

I need to write a function to calculate the fictitious value of some selected items in a website.

  • If The user Selects 1 item there is no discount and the value would be 1.
  • If The user Selects 8 items there would be a little discount and the value would be 7.
  • If The user Selects 24 items there would be a little discount and the value would be 20.
  • If The user Selects 40 items there would be a little discount and the value would be 30.
  • If The user Selects 80 items there would be a little discount and the value would be 50.

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:

  • If the user selects 5 items the value would be 5.
  • If the user selects 12 items the value would be 7+4 = 11.
  • If the user selects 23 items the value would be 7+7+7 = 21.
  • If the user selects 24 items the value would be 20.
  • If the user selects 77 items the value would be 30+20+7+5 = 62.
  • If the user selects 88 items the value would be 50+7 = 57.

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.

Whymarrh
  • 13,139
  • 14
  • 57
  • 108
Egidi
  • 1,736
  • 8
  • 43
  • 69

2 Answers2

2

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;
}
AlexAlvarez
  • 811
  • 5
  • 11
0

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
rdubya
  • 2,916
  • 1
  • 16
  • 20