我正在尝试编写一种算法,“购买x的m,免费获得n的y”,其中x和y是乘积的数量,m和n是一组乘积。免费商品应始终是价格最低的商品。
示例:
const a = { price: 1.0 }
const b = { price: 2.0 }
const c = { price: 3.0 }
const rule = {
x: 2,
y: 1,
m: [a,b,c],
n: [a,b]
}
// translate as "Buy any 2 items in [a,b,c] will get 1 item in [a,b] for free"
const cart = [a,b,c,a,b,c]
function getFoC(cart, rule) {
// find maximum number of item to be free
const max = maxAvailable(cart, rule)
// max = 2
// filter free-able item and sort by price
const sortedFreeable = cart.filter(i => rule.n.includes(i)).sort(priceComparator)
// sortedFreeable = [a,a,b,b]
// return the first max freeable item
return sortedFreeable.splice(0, m)
}
const foc = getFoC(cart, rule);
// output: [a,a]
难题出在maxAvailable()
蛮力逻辑将是:
// Step 1: Find all possible m & n combination
const combinationM = [[a,a], [a,b], [a,c], [b,b], [b,c], [c,c]]
const combinationN = [[a],[b]]
const combinationBoth = [[a,a,a],[a,a,b],[a,b,a],[a,b,b],[a,c,a],[a,c,b],[a,c,c],...]
// Step 2: find the maximum combination that can turn into cart base on combinationBoth.
const choices = [[a,b,b], [a,c,c]]
// where [a,b,b] and [a,c,c] is element of combinationBoth
// choice.flat() = [a,b,c,a,b,c] which equal to cart
return choices.length
我的问题是,第1步和第2步都具有无法接受的复杂性。 有什么更好的算法可以解决这个问题?