首页 > 解决方案 > 比萨促销的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

任何解决方案?

标签: javascript

解决方案


推荐阅读