我有购物车里的物品清单(假设每封信都是一个项目)
购物车列表= a,s,d,f,a,s,d,f,a
这是促销活动
购买1a并免费获得2d(在下面的逻辑中,1是srcNum,2是tarNum)
逻辑应该是渐进的。(每个2d应该是免费的)。对于上面的输入o/p应该是d,d
我做了一些像下面这样的东西。但是没有工作,任何帮助都很感激
Iterator tempIterator = tempList.iterator();
boolean targetCheck = false;
int check=0;
boolean runCompleted = false;
while (!runCompleted && tempIterator.hasNext()){
String itemCode = (String) tempIterator.next();
if(!targetCheck && targetItemsList.contains(itemCode) && check < tarNum){
tempIterator.remove();
check++;
}
else if (check >= tarNum && targetCheck == false) {
check = 0;
targetCheck = true;
}
else if (check < srcNum && targetCheck == true) {
tempIterator.remove();
Integer discountQuantity = discountedItems.get(itemCode);
if(null==discountQuantity) {
discountQuantity = 1;
}else {
discountQuantity++;
}
discountedItems.put(itemCode,discountQuantity);
check++;
}
else if (check >= srcNum && targetCheck == true) {
check = 0;
targetCheck = false;
}
if(tempList.size()==0){
runCompleted = true;
}else{
tempIterator = tempIterator = tempList.iterator();
}发布于 2022-01-28 10:47:04
您的折扣必须储存:项目a有2 d免费。因为java 9,所以可以使用record类。
record Discount(int itemCode, int free) {};
Map<Integer, Discount> itemCodeToDiscountMap = new HashMap<>();,如果2
a1d空闲,甚至2a1a空闲,这会变得更加复杂。但不是不恰当的。
你有一辆乱七八糟的推车,就像:
List<Item> cartList = new ArrayList<>();这是最好保存在一张地图的项目代码到数量。
Map<Integer, Integer> itemCodeToQuantityMap = new HashMap<>();在您的评估结束时,您将有:
Map<Integer, Integer> itemsToPay = new HashSet<>();
Map<Integer, Integer> itemsFree = new HashSet<>();
Map<Integer, Integer> itemsCouldTakeFree = new HashSet<>();所以a,a,b,d,a,a,b,d,d
第一步,简化购物车数据:
List<Item> cartList = new ArrayList<>();
...
Map<Integer, Integer> itemCodeToQuantityMap = new HashMap<>();
for (Item item: cartList) {
Item oldItem = itemCodeToQuantityMap.get(item.itemCode);
...
itemCodeToQuantityMap.get(item.itemCode, ...);
}然后
itemsToPay.putAll(itemCodeToQuantityMap);
for (Map.Entry<Integer, Integer> entry: itemCodeToQuantityMap.entrySet()) {
int itemCode = entry.getKey();
int quantity = entry.getValue();
Discount discount = itemCodeToDiscountMap.get(itemCode);
...
}首先,将itemCodeToQuantityMap复制到itemsToPay中意味着您不需要更改itemCodeToQuantityMap,但可以在itemsToPay中折扣/减去itemsToPay。
因为这是家务活的臭味,我就把它留在那里。只是一些小窍门:
https://stackoverflow.com/questions/70891980
复制相似问题