2014-12-07 28 views
2

我需要編寫一個函數來計算網站中某些選定項目的虛構值。堅持寫點折扣功能

  • 如果用戶選擇1個項目沒有折扣和值將是1。
  • 如果用戶選擇8個項目將有一個小的折扣和值將是7.
  • 如果用戶選擇24個項目將有一個小折扣,價值將是20.
  • 如果用戶選擇40項目將有一個小折扣,價值將是30.
  • 如果用戶選擇80項目那裏會是一個小折扣,價值將是50.

這些是僅有的4個折扣,但它們可以累積,所以如果用戶選擇110(80 + 24 + 6),該值應該是(50 + 20 + 6)。讓我們來看看一些其它例子:

  • 如果用戶選擇5個項目的值將是5。
  • 如果用戶選擇12個項目的值將是7 + 4 = 11
  • 如果用戶選擇23項的值將是7 + 7 + 7 = 21
  • 如果用戶選擇24個項目的值將是20。
  • 如果用戶選擇77項的值將是30 + 20 + 7 + 5 = 62.
  • 如果用戶選擇88個項目,該值將是50 + 7 = 57.

我希望我解釋一下自己。我可以猜到我需要使用mod邏輯運算符,但我不知道如何開始編寫這個算法,我想我需要一點幫助。

+0

它不應該是23的值嗎? 23 = 8 + 8 + 7 - > 7 + 7 + 7 = 21. – AlexAlvarez 2014-12-07 14:07:28

+0

你是對的,編輯過 – Egidi 2014-12-07 14:52:05

回答

2

JavaScript是不是我平時的編程語言,但這樣的事情應該工作。

這個想法是每次應用最好的折扣。要知道你可以多少次申請折扣,你只需要把剩下的購買物品和應用折扣所需要的物品之間的分割商,即如果你有17個物品,需要申請折扣8,17/8 = 2,剩下1個項目。然後,一旦你知道你應用折扣多少次,減去這些項目並繼續下去。

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; 
} 
0

下面是一些僞代碼,讓您開始:

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