How to find the smallest calculation value based on multiple variables?

Caveat: I use ColdFusion, but I feel that it can cover a wide range of languages, as this is more a programming issue, not just a ColdFusion issue.

Well, I was instructed to implement a code to apply promotions to items in a shopping cart. In principle, there can be any number of promotions for any number of items - for example, "Buy 2 ABC items, get 1 of the" ABC "items at 50%." However, there may also be a “buy 3 ABC items, get 1 from the“ ABC ”item for free.” Or even "buy 2" ABC "items, get 1 of the" XYZ "items at 50%."

So, imagine that in general, more product promotions work across the entire product.

Now I need to complete all possible scenarios in order to apply the promotion (or promotions) that give the customer the best possible value (lowest total).

However, I cannot figure out how to write code that will run through EVERY possible script. I can narrow down the number of promotions eligible to participate by filtering those that do not apply to items in the basket. Obviously, I also know the number of matching items in the basket.

So, let's say I have 5 items in my basket, and 3 of these items are eligible to participate (for example, above). 1 item has 3 possible promotions, another has 4 possible promotions, another has 2 possible promotions. My first thought is to go through every possible advertising campaign and within this cycle, with the exception of every possible order of suitable elements:

1-2-3 1-3-2 2-1-3 2-3-1 3-1-2 3-2-1

... and apply promotions every time, keeping the combination that produces the lowest amount.

Will this work? It's too much? Does anyone have a better suggestion?

Any code samples are welcome. Although I program this in ColdFusion, I can read / understand other languages ​​very well.

Thank.

+3
3

, , - , , ?

, , , ? , , ?

+3

, . , - . , .

.

def bestSetOfPromotions(cart, promotions, applied-promotions):
    if (len(promotions) == 0):     #no more choices
        return applied-promotions
    best-set = [] #best set of promotions found so far, the empty set.
    for next-promotion in promotions:
        if canApply(next-promotion, cart, applied-promotions):
            best = bestSetOfPromotions(cart, promotions.remove(next-promotion), applied-promotions.push(next-promotion))
            if (costOf(cart, best) < costOf(cart,best-set)):
               best-set = best
    return best-set

#we call it as such:
bestSetOfPromotions(cart, allThePromotions, [])

, . .

(canApply) , "". O (2 ^ len ()).

, .

+2

@Henry, , , . , , , :

  • (, ),
  • , , ( , ), , .
  • "" , (, ).

# 2 "", , .

, , , , , , , , "" , . , , , , . NP .

, "" . , , , : , ( , ). , . . - , "" .

+1

Source: https://habr.com/ru/post/1796166/


All Articles