javascript - 比萨促销的JS算法
问题描述
这个想法是,任何在当月在所有商店订购具有独特配料组合的三层配料比萨饼的客户都将通过电子邮件收到免费比萨饼的优惠券(如果他们提供了他们的电子邮件地址)。他们每个月都会生成一个文件,其中包含该月订购的所有比萨饼的 JSON 表示形式。每个比萨饼的配料按字母顺序排列如下:
monthly_data = [{"email": "email1@example.com", "toppings":
["Mushrooms","Pepperoni","Peppers"]},
{"email": "email2@example.com", "toppings":
["Cheddar","Garlic","Oregano"]},
{"email": "email3@example.com", "toppings": ["Bacon","Ham","Pineapple"]},
{"email": "", "toppings": ["Parmesan","Tomatoes"]},
{"email": "email4@example.com", "toppings":
["Mushrooms","Pepperoni","Peppers"]},
{"email": "", "toppings": ["Cheddar","Tomatoes"]},
{"email": "email5@example.com", "toppings": ["Bacon","Ham","Pineapple"]},
{"email": "email6@example.com", "toppings": ["Beef","Parmesan"]},
{"email": "", "toppings": ["Onions","Pepperoni"]},
{"email": "", "toppings": ["Bacon","Ham","Pineapple"]}]
function printWinners2(inputArray) {
let hashTable = new Map();
// Iterate through the array, with "order" being each item in the
//array.
inputArray.map((order)=>{
if(order.toppings !== null){
if((order.toppings.length === 3) && (order.email !== '')){
let toppingsAsString = order.toppings.toString().toLowerCase();
//console.log(toppingsAsString)
let matchingValue = hashTable.get(toppingsAsString)
/*hashTable.set(toppingsAsString,{email: order.email,
duplicate: false});*/
//console.log(hashTable.get(toppingsAsString))
if(matchingValue){
//console.log(matchingValue)
matchingValue.duplicate = true
//console.log(matchingValue)
} else{
hashTable.set(toppingsAsString,{email: order.email,
duplicate: false});
}
}
}
})
hashTable.forEach((value) => {
if (!value.duplicate) {
// Print out the email.
console.log(value.email);
}
});
}
printWinners2(monthly_data) //email2@example.com [printed answer as expected]
//But I want to test that algorithm with a different dataset.
//what if I use this array for testing
monthly_data = [{"email": "email1@example.com", "toppings":
["Artichoke","Shrimp","Bacon"]},
{"email": "email2@example.com", "toppings":
["Cheese"]},
{"email": "email3@example.com", "toppings": ["BACON","Ham","Pineapple"]},
{"email": "email5@example.com", "toppings": ["Bacon","Ham","Pineapple"]},
{"email": "email6@example.com", "toppings": ["Shrimp","Bacon","Artichoke"]},
{"email": "email7@example.com", "toppings":
["Artichoke","Chicken","Spinach"]},
{"email": "", "toppings": ["Onions","Pepperoni","Mushrooms"]},
{"email": "email8@example.com", "toppings": ["Mushrooms","Pepperoni","Onions"]},
{"email": "", "toppings": null}
]
预期的答案应该只有一个
email7@example.com
但它正在打印:
email1@example.com email6@example.com email7@example.com email8@example.com
任何解决方案?
解决方案
推荐阅读
- regex - 用于交替的正则表达式分组规则
- reactjs - 如何获取 React Native 元素的样式值?
- python - 为什么 json 库不接受我的报价?
- unity3d - 使用上下文 UnityEngine.Object 引发异常
- javascript - 如何在 React Native 的父组件内触发子组件 onPress
- c# - 如何使用自定义线条制作自定义按钮形状
- vba - VBA - MS Word 中的复制按钮
- amazon-web-services - 如何实现与 AWS EC2 的 10K 并发连接?
- javascript - 为每个新输入创建一个变量
- sql - 获取正确数据的 SQL 查询