
关于多商品优惠的算法难题
问题:
给你一批商品信息和它们的优惠折扣,以及你购买的商品清单,设计一个算法来计算使用这些优惠后能得到的最大折扣价格。
示例数据:
商品信息:
优惠信息:
购买清单:
答案:
使用回溯法可以解这个问题:
具体算法实现(javascript):
function compute(goods) {
// 分组满减信息
const discountsmap = new map();
for (const good of goods) {
for (const discountid of good.discounts) {
const discount = discountsmap.get(discountid);
if (!discount) {
discountsmap.set(discountid, []);
}
discountsmap.get(discountid).push(good);
}
}
// 回溯排列满减组合
const compose = [];
for (const [discountid, discountgroup] of discountsmap) {
backtrackcompose(
0,
discountgroup,
discountsmap.get(discountid)[0].full,
discountsmap.get(discountid)[0].reduction,
[],
compose,
discountid
);
}
// 组合选择
const result = { total: 0, discount: 0, compose: [] };
backtrackselect(0, compose, [], new set(), result, 0);
result.total -= result.discount;
return result;
}
// 回溯排列满减组合
function backtrackcompose(start, goods, target, discount, memo, res, disid) {
if (target <= 0) {
res.push([...memo]);
return;
}
for (let i = start; i < goods.length; i++) {
const g = goods[i];
if (memo.some((c) => c[0] === g.id)) continue;
memo.push([g.id, discount, g.totalprice * (1 - g.discount), disid]);
backtrackcompose(i + 1, goods, target - g.totalprice * (1 - g.discount), discount, memo, res, disid);
memo.pop();
}
}
// 组合选择
function backtrackselect(start, composes, trace, memo, res, discount) {
if (discount > res.discount) {
res.discount = discount;
res.compose = [...trace];
}
for (let i = start; i < composes.length; i++) {
const cmp = composes[i];
if (cmp.some((c) => memo.has(c[0]))) continue;
trace.push(cmp);
cmp.foreach((c) => memo.add(c[0]));
backtrackselect(i + 1, composes, trace, memo, res, discount + cmp[0][1]);
trace.pop();
cmp.foreach((c) => memo.delete(c[0]));
}
}计算示例:
const goods = [
{ id: 1, name: "a", price: 10, discounts: [101, 102, 105] },
{ id: 2, name: "b", price: 6, discounts: [101, 102, 105, 106] },
{ id: 3, name: "c", price: 7, discounts: [101, 103, 107] },
];
const buylist = [
{ id: 1, num: 3 },
{ id: 2, num: 6 },
{ id: 3, num: 3 },
];
const result = compute(goods, buylist);
console.log(result);输出结果:
{
total: 93.1,
discount: 11,
compose: [
[[1, 6, 28.5, 102], [2, 6, 25.2, 102]],
[[4, 5, 33.6, 104]],
],
}在这个示例中,最终计算出的总价为 93.1 元,总折扣为 11 元,所使用的满减组合是 "[1, 6, 28.5, 102]", "[2, 6, 25.2, 102]" 和 "[4, 5, 33.6, 104]」。
以上就是如何设计算法来计算多商品优惠后的最大折扣?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号