大致的思路是这样的,先计算单个商品的多件折扣先,然后得出每个商品的总价格
折扣类型的优惠不需要混合计算,只需要单个商品计算即可,主要是满减优惠,是多商品组合计算的
然后根据每个商品享受的公共满减优惠,组合出最大的优惠,优惠过的商品不能再和其他的商品优惠
有没有大佬用JavaScript或者java实现一遍,救救孩子吧
图片看不清楚可以点击这个看大图
https://image-static.segmentf...
数据库的数据是这样子的
let { multiply } = require("mathjs");
let tb_goods = [
{
id: 1,
goodsName: "A",
price: 10,
// 绑定的优惠折扣
spceList: [101, 102, 105],
},
{
id: 2,
goodsName: "B",
price: 6,
spceList: [101, 102, 105, 106],
},
{
id: 3,
goodsName: "C",
price: 7,
spceList: [101, 103, 107],
},
{
id: 4,
goodsName: "D",
price: 7,
spceList: [101, 104, 107],
},
];
let tb_spce = [
{
id: 101,
type: "满减",
msg: "满20减2",
full: 20,
reduction: 2,
},
{
id: 102,
type: "满减",
msg: "满35减6",
full: 35,
reduction: 6,
},
{
id: 103,
type: "满减",
msg: "满28减3",
full: 28,
reduction: 3,
},
{
id: 104,
type: "满减",
msg: "满30减5",
full: 30,
reduction: 5,
},
{
id: 105,
type: "折扣",
msg: "2件9.5折",
full: 2,
reduction: 0.95,
},
{
id: 106,
type: "折扣",
msg: "3件7折",
full: 3,
reduction: 0.7,
},
{
id: 107,
type: "折扣",
msg: "2件8折",
full: 2,
reduction: 0.8,
},
];
// 测试购买的商品,3个A,6个B,3个C
let testBuy = [
{
goodsId: 1,
num: 3,
},
{
goodsId: 2,
num: 6,
},
{
goodsId: 3,
num: 3,
},
];
testBuy.map((buyItem) => {
// 先找到购买的这个商品的数据
let goodsInfo = tb_goods.find((goodsItem) => goodsItem.id == buyItem.goodsId);
// 得到这个商品的折扣优惠数据
let spceList = [];
tb_spce.filter((spceItem) => {
if (goodsInfo.spceList.includes(spceItem.id)) {
spceList.push(spceItem);
}
});
// 得出总价
let money = multiply(goodsInfo.price, buyItem.num);
// 备用的总价,为了计算折扣使用
let money2 = multiply(goodsInfo.price, buyItem.num);
spceList.map((spceItem) => {
// 是折扣类型的
if (spceItem.type === "折扣") {
// 满足大于x件
if (buyItem.num >= spceItem.full) {
console.log(spceItem.reduction);
let reducMoney = multiply(money2, spceItem.reduction);
if (reducMoney < money) {
money = reducMoney;
}
}
}
buyItem.money = money;
});
});
console.log(testBuy);
// [
// { goodsId: 1, num: 3, money: 28.5 },
// { goodsId: 2, num: 6, money: 25.2 },
// { goodsId: 3, num: 3, money: 16.8 }
// ]
// 最后得出这段数据,然后再次根据多个商品组合出来的满减优惠得出总价格
组合优惠卷问题,基础算法可以使用
回溯法
遍历所有可能性。下面是参照你的数据格式写的算法,返回结果格式如下: